我正在构建一个与 API Gateway 集成的 AWS Lambda 服务器,但无法公开该服务器以便将其挂接到 Express 中。我想知道是否有人知道在没有 Express 的情况下使用中间件的最佳实践。
这是我的代码。
var jobs = require('./jobs');
var http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
//I want to be able to add a function here that executes all of the middleware that I specify.
const { headers, method, url } = req;
let body = [];
if(url)
enableCors(res);
res.writeHead(200, {'Content-Type': 'application/json'})
const resBody = { headers, method, url, body };
res.write(JSON.stringify(resBody));
res.end();
}).listen(8080);
我想要一个类似于 Express 的东西,我可以写这样的东西,服务器就会知道在该目录中搜索我的路线。
server.use('/api', require('./api'))
最佳答案
由于您想要的是使用 express
对 API 网关进行本地模拟,因此这是我在项目中使用的内容。
这不需要无服务器
或claudiajs
。
我也总是只使用 Lambda 代理集成,因此它更简单。
类似这样的事情...
const bodyParser = require('body-parser')
const cors = require('cors')
const express = require('express')
// Two different Lambda handlers
const { api } = require('../src/api')
const { login } = ('../src/login')
const app = express()
app.use(bodyParser.json())
app.use(cors())
// route and their handlers
app.post('/login', lambdaProxyWrapper(login))
app.all('/*', lambdaProxyWrapper(api))
app.listen(8200, () => console.info('Server running on port 8200...'))
function lambdaProxyWrapper(handler) {
return (req, res) => {
// Here we convert the request into a Lambda event
const event = {
httpMethod: req.method,
queryStringParameters: req.query,
pathParameters: {
proxy: req.params[0],
},
body: JSON.stringify(req.body),
}
return handler(event, null, (err, response) => {
res.status(response.statusCode)
res.set(response.headers)
return res.json(JSON.parse(response.body))
})
}
}
然后,使用 nodemon
运行它,以便它监视文件并根据需要重新加载。
nodemon --watch '{src,scripts}/**/*.js' scripts/server.js
关于node.js - 没有 Express 的 Node 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48288898/