直接从客户端调用Post API时发生CORS错误

时间:2019-04-01 23:22:48

标签: reactjs amazon-web-services

我有一个经过测试的帖子功能,并且运行正常。从前端调用它时,出现以下错误:

quantiles = [.25, .50, .75]
results = OrderedDict([(x,[]) for x in quantiles])
columns = ["age", "height"]

for csv_file in os.listdir(file_path):
    df = pd.read_csv(os.path.join(file_path, csv_file))
    for column in columns:
        for value in quantiles:
            results[value].append(df[column].quantile(value))

result_df = pd.DataFrame(data=results, index=columns)

我尝试禁用CORS并使用不同的Cognito身份池来允许不同的权限,但是我仍然遇到相同的错误。在AWS中对其进行测试时,它成功并且没有错误。

我在这里调用API:

Access to XMLHttpRequest at 'https://sdigg5u4xb.execute-api.eu-west-1.amazonaws.com/prod/sites' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是我在serverless.yml文件中定义函数的地方:

import { API } from "aws-amplify";

export default (async function submitSite(values) {
  console.log(values);
  return API.post("sites", "/sites", {
    body: values
  }) 
});

1 个答案:

答案 0 :(得分:0)

我建议您检查这些。

  • 确保按照here
  • 的说明在API网关中启用CORS
  • 请确保您的服务器较少的应用启用了CORS here
  • 别忘了在函数中添加Access-Control-Allow-Origin响应标头。

    module.exports.hello = function(event, context, callback) {
    
    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
        "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
      },
      body: JSON.stringify({ "message": "Hello World!" })
    };
    
    callback(null, response);