Cette API REST dans AWS Amplify est créée avec les commandes ci-dessous. Sans modifier le code de la fonction Express générée, la requête postée ci-dessous génère l'erreur suivante :
Access to XMLHttpRequest at 'https://example-id.execute-api.ca-central-1.amazonaws.com/dev/example-path' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
La fonction Express contient par défaut du code pour éviter les problèmes CORS sous le commentaire Enable CORS for all methods
à la ligne 21
. Que peut-on faire pour permettre aux requêtes d'être transmises à la fonction API ?
Code Express par défaut dans app.js (backend)
// Enable CORS for all methods
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
});
// Example POST method
app.post('/example-path', function(req, res) {
// Add your code here
res.json({success: 'post call succeed!', url: req.url, body: req.body})
});
Amplifier les ordres
amplify add api
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the project: example
? Provide a path (e.g., /book/{isbn}): /example-path
? Choose a Lambda source Create a new Lambda function
? Provide a friendly name for your resource to be used as a label for this category in the project: example
? Provide the AWS Lambda function name: example
? Choose the runtime that you want to use: NodeJS
? Choose the function template that you want to use: Serverless ExpressJS function (Integration with API Gateway)
? Do you want to access other resources in this project from your Lambda function? No
? Do you want to invoke this function on a recurring schedule? No
? Do you want to configure Lambda layers for this function? No
? Do you want to edit the local lambda function now? No
? Restrict API access Yes
? Who should have access? Authenticated users only
? What kind of access do you want for Authenticated users? create, update, delete
? Do you want to add another path? No
amplify push
Composant.js
const apiName = 'example';
const path = '/example-path';
const myInit = {
body: JSON.stringify({
example: example,
})
};
API
.post(apiName, path, myInit)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});