![](/img/trans.png)
[英]No 'Access-Control-Allow-Origin' header is present on the requested resource (AWS, API Gateway, S3, CORS)
[英]ReactJS + AWS API Gateway : No 'Access-Control-Allow-Origin' header is present on the requested resource?
这是我的第一篇文章。 I am new to ReactJS and AWS, I keep getting a CORS error when I try to connect my form.js file with an AWS API by using axios.post() function. 在过去的 3 天里,我尝试了所有可能的事情,但没有任何运气,我不知道我做错了什么,我尝试在 AWS API 网关中启用 CORS。 那里也没有运气。 有人可以帮忙吗!!
这是我的 form.js 代码:
import React, { Component } from 'react';
import axios from 'axios';
export default class Form extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
dob: '',
major: '',
univ: '',
desiredcareer: '',
typeofopp: '',
collegestressor: '',
stresslevel: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
this.handleDOBChange = this.handleDOBChange.bind(this);
this.handleMajorChange = this.handleMajorChange.bind(this);
this.handleUnivChange = this.handleUnivChange.bind(this);
this.handleDesiredCareerChange = this.handleDesiredCareerChange.bind(this);
this.handleTypeOfOppChange = this.handleTypeOfOppChange.bind(this);
this.handleCollegeStressorChange = this.handleCollegeStressorChange.bind(this);
this.handleStressLevelChange = this.handleStressLevelChange.bind(this);
}
handleNameChange = (event) => {
this.setState({
name: event.target.value
});
}
handleDOBChange = (event) => {
this.setState({
dob: event.target.value
});
}
handleMajorChange = (event) => {
this.setState({
major: event.target.value
});
}
handleUnivChange = (event) => {
this.setState({
univ: event.target.value
});
}
handleDesiredCareerChange = (event) => {
this.setState({
desiredcareer: event.target.value
});
}
handleTypeOfOppChange = (event) => {
this.setState({
typeofopp: event.target.value
});
}
handleCollegeStressorChange = (event) => {
this.setState({
collegestressor: event.target.value
});
}
handleStressLevelChange = (event) => {
this.setState({
stresslevel: event.target.value
});
}
async handleSubmit(event) {
event.preventDefault();
const { name,dob,major,univ,desiredcareer,typeofopp,collegestressor,stresslevel } = this.state;
await axios.post(
"https://4hpnc7h0fa.execute-api.us-west-2.amazonaws.com/Test/enterdetails/jujiPutUserDetails",
{ key1: `${name}`,
key2: `${dob}`,
key3: `${major}`,
key4: `${univ}`,
key5: `${desiredcareer}`,
key6: `${typeofopp}`,
key7: `${collegestressor}`,
key8: `${stresslevel}`
}
);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>Name:</label>
<input
type="text"
name="name"
onChange={this.handleNameChange}
value={this.state.name}
/>
<label>Date Of Birth (MM/DD/YYYY):</label>
<input
type="text"
name="dob"
onChange={this.handleDOBChange}
value={this.state.dob}
/>
<label>Major:</label>
<input
type="text"
name="major"
onChange={this.handleMajorChange}
value={this.state.major}
/>
<label>University:</label>
<input
type="text"
name="univ"
onChange={this.handleUnivChange}
value={this.state.univ}
/>
<label>Desired Career Field:</label>
<input
type="text"
name="desiredcareer"
onChange={this.handleDesiredCareerChange}
value={this.state.desiredcareer}
/>
<label>Type Of Opportunity Wanted:</label>
<input
type="text"
name="typeofopp"
onChange={this.handleTypeOfOppChange}
value={this.state.typeofopp}
/>
<label>College Stressor Factor:</label>
<input
type="text"
name="collegestressor"
onChange={this.handleCollegeStressorChange}
value={this.state.collegestressor}
/>
<label>Stress Level (1-10):</label>
<input
type="text"
name="stresslevel"
onChange={this.handleStressLevelChange}
value={this.state.stresslevel}
/>
<button type="submit">Submit Information</button>
</form>
</div>
);
}
}
错误:
Access to XMLHttpRequest at 'https://4hpnc7h0fa.execute-api.us-west-
2.amazonaws.com/Test/enterdetails/jujiPutUserDetails' 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.
xhr.js:155 POST https://4hpnc7h0fa.execute-api.us-west-
2.amazonaws.com/Test/enterdetails/jujiPutUserDetails net::ERR_FAILED
Uncaught (in promise) Error: Network Error
at createError (createError.js:17)
at XMLHttpRequest.handleError (xhr.js:69)
更新:
这是我的 Lambda Function 代码:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: "us-west-2"});
exports.handler = (event, context, callback) => {
console.log("Processing...");
const params = {
Item: {
userID: context.awsRequestId,
name: JSON.stringify(event.key1),
dob: JSON.stringify(event.key2),
major: JSON.stringify(event.key3),
univ: JSON.stringify(event.key4),
desiredcareer: JSON.stringify(event.key5),
typeofopp: JSON.stringify(event.key6),
collegestressor: JSON.stringify(event.key7),
stresslevel: JSON.stringify(event.key8)
},
TableName: "jujiuseronboarding"
};
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': 'https://localhost:3000/'
},
body: JSON.stringify('Item Added Successfully!'),
};
docClient.put(params, function(err, data) {
if(err){
callback(err, null);
} else {
callback(null, data);
}
})
};
任何帮助将不胜感激: :)
现在,您没有在响应中发送标头。 所以我在 Dynamodb 的 else 语句中评论了回调 put function 并在最后放置了一个回调以发送带有标题的响应(这基本上是响应变量)
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: "us-west-2"});
exports.handler = (event, context, callback) => {
console.log("Processing...");
const params = {
Item: {
userID: context.awsRequestId,
name: JSON.stringify(event.key1),
dob: JSON.stringify(event.key2),
major: JSON.stringify(event.key3),
univ: JSON.stringify(event.key4),
desiredcareer: JSON.stringify(event.key5),
typeofopp: JSON.stringify(event.key6),
collegestressor: JSON.stringify(event.key7),
stresslevel: JSON.stringify(event.key8)
},
TableName: "jujiuseronboarding"
};
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*' // changed this
},
body: JSON.stringify('Item Added Successfully!'),
};
docClient.put(params, function(err, data) {
if(err){
callback(err, null);
} else {
// callback(null, data);
}
});
callback(null, response);
};
您能否检查 API 网关控制台中是否启用了 CORS?
对于任何更新请求(POST、PUT 等),API 网关希望为飞行前请求启用 OPTIONS。 可以请您检查它是否已启用?
如果未启用,请求调用将失败并出现 CORS 错误。 对于 GET 请求,此 OPTIONS 不是必需的。
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
https://enable-cors.org/server_awsapigateway.html
如果 CORS 已启用,您能否按照其中提到的步骤进行测试,看看它是否正常工作?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.