我有一个无服务器的快速应用程序。在应用程序中,我有一个名为“/”的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(或其他promise请求库)调用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 没有 请求的 资源。因此,源“mydomain”不是 允许访问。js:31交叉源读取阻塞(corb)阻塞 交叉源响应 https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/开发 用哑剧 输入application/json。见 https://www.chromestatus.com/feature/5629709824032768 为了更多 细节。
API网关配置:
我同意@kmo。很确定这是一个cors的问题。NPM中有一个模块正是为了这个目的,请阅读 here .
要安装它,请运行 npm install -s cors
npm install -s cors
然后在您的Express应用程序中,添加以下内容:
const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors());