简体   繁体   English

使用API​​网关反应调用Node.js PUT Lambda函数

[英]React calling a Node.js PUT Lambda function with API Gateway

I've been reading through different questions and answers on the site and haven't been able to solve my issue. 我一直在阅读网站上的各种问题和答案,但无法解决我的问题。

I'm trying to create a serverless CRUD App with React using Lambda functions and a DynamoDB database. 我正在尝试使用Lambda函数和DynamoDB数据库使用React创建一个无服务器的CRUD应用程序。

I have the GET and POST functions working. 我有GET和POST函数。 I am working on the PUT and DELETE now. 我正在处理PUT和DELETE。

I am using localhost to test. 我正在使用localhost进行测试。

This is my code calling the lambda, 这是我的代码,称为lambda,

onSubmit = (event) => {
        event.preventDefault();
        console.log('onSubmit state', this.state);

        const { id, record, album, artist, date, imageUrl } = this.state;

        fetch("https://link.execute-api.us-east-1.amazonaws.com/RecordShop/", {
            method: 'PUT',
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
            },      
            body: JSON.stringify({records: id, record, album, artist, date, imageUrl})
        });

        // this.props.getRecords();
        this.handleClose(); 

    }

This is my PUT Lambda function 这是我的PUT Lambda函数

console.log('Loading function');
let doc = require('dynamodb-doc');
let db = new doc.DynamoDB();

exports.handler = function(event, context) {
    let item = {
        "id" : event.id,
        "record" : event.record,
        "album" :  event.album,
        "artist" : event.artist,
        "date" : event.date,
        "imageUrl" : event.imageUrl
    };
     let params = {
         TableName: process.env.TABLE_NAME, 
         Item: item
    };
        console.log(params);
    db.putItem(params,function(err,data){
        if (err) console.log(err);
        else console.log(data);
    });
};

With the PUT request, I am able to successfully test it in my Lambda function and have it update the database. 有了PUT请求,我就能在Lambda函数中成功测试它并让它更新数据库。 I am using Chrome and have seen that it doesn't do CORS so I've installed a Chrome extension that allows it and have set the incoming URLs to localhost. 我正在使用Chrome,并且看到它不能执行CORS,所以我安装了允许它使用的Chrome扩展程序,并将传入的URL设置为localhost。 I have also tried Firefox and received the following error, 我也尝试使用Firefox并收到以下错误,

Cross-Origin Request Blocked: The Same Origin Policy disallows reading 
the remote resource at https://vv2qx5zqb7.execute-api.us-east- 
1.amazonaws.com/Dev/. (Reason: missing token ‘access-control-allow- 
origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS 
preflight channel).[Learn More]"

From this, I followed the learn more and saw this, 我从中了解了更多,并看到了这一点,

"The response to the CORS request is missing the required Access-Control-Allow-Origin header, which is used to determine whether or not the resource can be accessed by content operating within the current origin." “对CORS请求的响应缺少必需的Access-Control-Allow-Origin标头,该标头用于确定当前源内操作的内容是否可以访问资源。”

So I added the Allow-Origin to my react header code as recommended and it didn't work. 所以我按照建议将Allow-Origin添加到了我的react标头代码中,但是它没有用。

headers: {
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json'
        },     

In Chrome I'm getting this error, 在Chrome浏览器中,我收到此错误,

Access to fetch at 'https://execute-api.us-east- 
1.amazonaws.com/stagename/' from origin 'http://localhost:3000' has 
been 
blocked by CORS policy: Request header field access-control-allow- 
origin is not allowed by Access-Control-Allow-Headers in preflight 
response.

So I looked and played around with the API Gateway set up and tried enabling a Lambda Proxy integration with my put request and get request with no luck. 因此,我环顾了API网关的设置,并尝试启用Lambda代理与我的put请求和get请求的集成,但没有成功。

I know it's a connection issue between my code call and the API Gateway I'm just not sure what I need to change in the gateway to get it to accept the changes. 我知道这是我的代码调用和API网关之间的连接问题,我只是不确定我需要在网关中进行哪些更改才能使其接受更改。

If anyone has any ideas I would really appreciate it. 如果有人有任何想法我会非常感激。

You need to attach Access-Control-Allow-Origin in the response from your server. 您需要在服务器的响应中附加Access-Control-Allow-Origin It has no value if attached by the client in the request. 如果客户端在请求中附加了它,则没有任何值。 Your Lambda response should look like: 您的Lambda响应应如下所示:

{
  statusCode: 200,
  headers: {
    'Access-Control-Allow-Origin': 'https://yourdomain.com' // Or use wildard * for testing
  },
  body: JSON.stringify(data)
}

If Lambda runtime is Node.js 8.10 如果Lambda运行时是Node.js 8.10

console.log('Loading function');
let doc = require('dynamodb-doc');
let db = new doc.DynamoDB();

exports.handler = (event) => {

    function formatResponse(data, code) {
      return { 
        statusCode: code,
        headers: {
          'Access-Control-Allow-Origin': 'https://yourdomain.com' // Or use wildard * for testing
        },
        body: JSON.stringify(data)
      }
    }

    let item = {
      "id" : event.id,
      "record" : event.record,
      "album" :  event.album,
      "artist" : event.artist,
      "date" : event.date,
      "imageUrl" : event.imageUrl
    };

    let params = {
      TableName: process.env.TABLE_NAME, 
      Item: item
    };

    console.log(params);

    db.putItem(params, function(err, data) {
      if (err) return formatResponse(err, 400);
      else return formatResponse(data, 200);
    });
};

If Lambda runtime is < Node.js v8.10 如果Lambda运行时是<Node.js v8.10

console.log('Loading function');
let doc = require('dynamodb-doc');
let db = new doc.DynamoDB();

exports.handler = (event, context, callback) => {

    function formatResponse(data, code) {
      return { 
        statusCode: code,
        headers: {
          'Access-Control-Allow-Origin': 'https://yourdomain.com' // Or use wildard * for testing
        },
        body: JSON.stringify(data)
      }
    }

    let item = {
      "id" : event.id,
      "record" : event.record,
      "album" :  event.album,
      "artist" : event.artist,
      "date" : event.date,
      "imageUrl" : event.imageUrl
    };

    let params = {
      TableName: process.env.TABLE_NAME, 
      Item: item
    };

    console.log(params);

    db.putItem(params, function(err, data) {
      if (err) callback(null, formatResponse(err, 400));
      else callback(null, formatResponse(data, 200));
    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AWS Lambda 与 API 网关和 Node.js 返回 HTTP 50 - AWS Lambda with API gateway and Node.js returning HTTP 502 AWS API 网关与 Lambda HTTP GET 请求(Node.js)502 错误网关 - AWS API Gateway with Lambda HTTP GET Request (Node.js) 502 Bad Gateway 如何从AWS Lambda Node.js 8.10异步函数向AWS API网关返回net.socket数据? - How to return net.socket data from AWS Lambda Node.js 8.10 async function to AWS API gateway? 如何使用无服务器框架通过 AWS API 网关在 Node.js 中编写的 AWS Lambda function 上返回错误? - How do I return errors on an AWS Lambda function written in Node.js through the AWS API Gateway using the Serverless framework? 通过Node.JS使用REST API以获得AWS Lambda函数 - Consuming an REST API with Node.JS for a AWS Lambda Function Calling AWS Lambda function from another Lambda function using node.js - Calling AWS Lambda function from another Lambda function using node.js 如何使用 SAM CLI 部署 API 网关、Lambda(Node.js) 和 DynamoDB? - How to deploy API gateway, Lambda(Node.js) and DynamoDB using SAM CLI? AWS Lambda/API 网关 - 传递 ID 以使用 node.js 在 mysql 中删除一行 - AWS Lambda/API Gateway - Pass an ID to delete a row in mysql with node.js AWS + API网关+ Lambda + Node.js在Google上的操作ApiAiApp - AWS + API Gateway + Lambda + Node.js actions-on-google ApiAiApp 使用 node.js 从 AWS Lambda 将自定义错误传回 AWS API Gateway - Passing custom errors back to AWS API Gateway from AWS Lambda using node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM