【问题标题】:Express lambda return JSON from api callExpress lambda 从 api 调用返回 JSON
【发布时间】:2018-11-27 06:37:45
【问题描述】:

我有一个无服务器快递应用。在应用程序中,我有一个名为“/”的 app.get,它应该调用一个 api,从 api 检索数据并将其发送回用户。

https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/dev

我可以在返回的页面上看到 json 格式的数据。

这是我的 lambda 函数的 index.js:

const serverless = require('serverless-http');
const express = require('express');
const request = require('request');
const app = express()

app.get('/', function (req, res) {

  var options = { method: 'POST',
   url: 'https://some.api.domain/getTopNstc',
   headers:
    {   'Content-Type': 'application/json' },
   body: {},
   json: true
  };

  request(options, function (error, response, body) {
    console.log('request call')
   if (error) throw new Error(error);
  // res.status(200).send(response);
  res.json(response);
  });
});

module.exports.handler = serverless(app);

但是我希望能够通过 axios(或其他承诺请求库)调用 lambda '/'

我尝试使用以下代码来调用我的 lambda:

axios.get('https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/dev', {
  headers: {
    'Content-Type': 'application/json',
   },
  body:{}
  }).then((res) => {
  console.log(res);
 });

加载失败 https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/dev:没有 请求中存在“Access-Control-Allow-Origin”标头 资源。因此,Origin 'myDomain' 不是 允许访问。 bundle.js:31 跨域读取阻塞 (CORB) 被阻止 跨域响应 https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/dev 带 MIME 输入应用程序/json。看 https://www.chromestatus.com/feature/5629709824032768 了解更多 详情。

API 网关配置:

【问题讨论】:

标签: amazon-web-services express cors aws-lambda cross-origin-read-blocking


【解决方案1】:

我同意@KMo。很确定这是一个 CORS 问题。 npm 中有一个专门用于此目的的模块,请阅读它here

要安装它,请运行npm install -s cors

然后在您的 express 应用中,添加以下内容:

const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors());

【讨论】:

    猜你喜欢
    • 2019-04-01
    • 2013-10-18
    • 1970-01-01
    • 2021-11-22
    • 2019-08-21
    • 2021-01-31
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    相关资源
    最近更新 更多