架构的CORS错误"/>
Express Node.JS后端,React前端和AWS基础架构的CORS错误
我有一个React前端,允许用户添加和查看包含文本和图片的食谱。 后端是一个Express Node.JS应用程序,它可以读取和写入DynamoDB数据库。 该应用程序使用无服务器框架部署在AWS上,因此它使用API Gateway,Lambda,DynamoDB和S3进行照片存储。 我正在努力让uploadphoto路由工作,但CORS错误阻止它工作。
我已经导入了cors NPM模块并在应用程序上使用它。 我已经尝试明确指定配置中的原点,但这没有什么区别。 我也有cors:在我的serverless.yml文件中的每个路由都是true。
serverless.yml excerpt:
service: recipes-api
provider:
name: aws
runtime: nodejs8.10
stage: dev
region: us-east-1
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource:
- { "Fn::GetAtt": ["RecipesDynamoDBTable", "Arn"] }
environment:
RECIPES_TABLE: ${self:custom.tableName}
S3_BUCKET: ${self:custom.bucketName}
functions:
app:
handler: index.handler
events:
- http: ANY /
- http: 'ANY {proxy+}'
getRecipe:
handler: index.handler
events:
- http:
path: recipes/{name}
method: get
cors: true
allRecipes:
handler: index.handler
events:
- http:
path: allrecipes
method: get
cors: true
addRecipe:
handler: index.handler
events:
- http:
path: recipes
method: post
cors: true
uploadPhoto:
handler: index.handler
events:
- http:
path: uploadphoto
method: post
cors: true
getPhoto:
handler: index.handler
events:
- http:
path: photo/{name}
method: get
cors: true
index.js excerpt:
const serverless = require('serverless-http');
const express = require('express');
const app = express();
const AWS = require('aws-sdk');
const cors = require('cors');
...
app.use(cors({origin: ''}))
//Upload Photo Endpoint
app.post('/uploadphoto', function (req, res) {
const s3 = new AWS.S3(); // Create a new instance of S3
const fileName = req.body.fileName;
const fileType = req.body.fileType;
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 500,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if(err){
console.log(err);
res.json({success: false, error: err})
}
// Data payload of what we are sending back, the url of the signedRequest and a URL where we can access the content after its saved.
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws/${fileName}`
};
// Send it all back
res.json({success:true, data:{returnData}});
});
})
AddRecipeForm.js excerpt:
handleUpload = (ev) => {
console.log("handleUpload")
console.log(ev)
let file = this.uploadInput.files[0];
// Split the filename to get the name and type
let fileParts = this.uploadInput.files[0].name.split('.');
let fileName = fileParts[0];
let fileType = fileParts[1];
console.log("Preparing the upload");
axios.post("",{
fileName : fileName,
fileType : fileType
})
.then(response => {
var returnData = response.data.data.returnData;
var signedRequest = returnData.signedRequest;
var url = returnData.url;
this.setState({url: url})
console.log("Recieved a signed request " + signedRequest);
// Put the fileType in the headers for the upload
var options = {
headers: {
'Content-Type': fileType
}
};
axios.put(signedRequest,file,options)
.then(result => {
console.log("Response from s3")
this.setState({success: true});
})
.catch(error => {
console.error(error);
})
})
.catch(error => {
console.error(error);
})
}
单击在AddRecipeForm.js中调用handleUpload函数的Upload Photo按钮时,我在控制台中收到以下错误:
Origin is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load due to access control checks.
Failed to load resource: Origin is not allowed by Access-Control-Allow-Origin.
请注意,每个其他路由都有效(getRecipe,allRecipes,addRecipe)并发送CORS标头,因此我不确定为什么我从React到API网关的addphoto请求不发送CORS标头,即使它应该在索引中使用它。 JS。 在此先感谢您的帮助!
回答如下:您的serverless.yml具有默认定义的函数'app',这是一个包罗万象的路由({proxy +}匹配所有)。 它看起来就像你正在击中的路线而不是uploadPhoto,因为你的uploadPhoto路线被定义为方法POST,但你的前端axios请求正在使用PUT。
更多推荐
Express Node.JS后端,React前端和AWS基础架构的CORS错误
发布评论