在Express JS中从AWS Lambda进行外部API调用

时间:2018-06-26 10:02:31

标签: node.js amazon-web-services express aws-lambda

我想使用aws lambda服务从express.js发出外部HTTP请求,但出现以下错误:

{
  "statusCode": 502,
  "body": "",
  "headers": {}
}

看来我无法通过express js进行外部HTTP调用。有人可以让我知道为什么我得到这个错误。快速解决方案会有所帮助。

我有一个快递服务器,如下所示: 文件名:app.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http').Server(app);
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
var request = require('request');


app.get('/fake-json', function(req, res) {
    request({
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        method: 'GET',
        json: true
    }, function (error, response, body){
        res.status(201).json({'data' : body}); 
        //req.headers['x-apigateway-context'].done(null, '');
        res.end();    
    });
})

const PORT = 8090;
http.listen(PORT, function(err) {
    if(!err) {
        console.log('Node server Server running @ ' + PORT);
    }
    else {
        console.log('Error while running server');
    }
});


module.exports = app;

lambda的配置如下:

文件名:lambda.js

'use strict'

const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app');
const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context) => {
    console.log("EVENT: ", JSON.stringify(event));
    awsServerlessExpress.proxy(server, event, context);
}

0 个答案:

没有答案