【问题标题】:ReactJS + AWS API Gateway : No 'Access-Control-Allow-Origin' header is present on the requested resource?ReactJS + AWS API Gateway:请求的资源上没有“Access-Control-Allow-Origin”标头?
【发布时间】:2020-10-23 14:27:59
【问题描述】:

这是我的第一篇文章。我是 ReactJS 和 AWS 的新手,当我尝试使用 axios.post() 函数将我的 form.js 文件与 AWS API 连接时,我不断收到 CORS 错误。在过去的 3 天里,我尝试了所有可能的事情,但没有任何运气!我不知道我做错了什么,我尝试在 AWS API Gateway 中启用 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 函数代码:

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);
        }
    })
};

任何帮助将不胜感激! :)

【问题讨论】:

  • 您的 API 是否受 Lambda 支持?
  • 我上次使用了相同的堆栈并遇到了相同的问题。有几个因素可以导致它。在回答问题之前需要更多信息
  • @hephalump 是的!
  • @NghiaDo 您还需要什么其他信息? Lambda 函数定义?
  • 您的 Lambda 响应需要包含 CORS 标头...

标签: javascript reactjs amazon-web-services aws-lambda aws-api-gateway


【解决方案1】:

现在您没有在响应中发送标头。所以我在 Dynamodb put 函数的 else 语句中注释了回调,并在最后放置了一个回调,用于发送带有标题的响应(基本上是响应变量)

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);

};

【讨论】:

  • 您好!我尝试将此代码添加到我的 Lambda 函数中,并在 AWS API Gateway 中启用了 cors,但仍然出现 CORS 错误:( 谢谢您的回答!
  • 很高兴能帮到你!!
【解决方案2】:

您能否检查一下 API Gateway 控制台中是否启用了 CORS?

对于任何更新请求(POST、PUT 等),API Gateway 期望为飞行前请求启用 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 已启用,您能否按照其中提到的步骤进行测试并查看它是否正常工作?

【讨论】:

  • 嘿!我尝试了您的链接,并且修改了我的 lambda 函数,我能够启动并运行它!非常感谢您的回答! :D
猜你喜欢
  • 2017-04-28
  • 2017-02-07
  • 2021-06-29
  • 2023-03-16
  • 2014-07-30
  • 2016-01-14
  • 2023-03-15
  • 2018-12-02
  • 2021-04-15
相关资源
最近更新 更多