node.js - 没有 Express 的 Node 中间件

标签 node.js aws-lambda aws-api-gateway

我正在构建一个与 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/

相关文章:

javascript - nodeJS 异步与同步

amazon-web-services - AWS SAM 模板 : Issue mapping S3 events to Lambda

python - 如何在本地测试 aws lambda 函数

amazon-web-services - 在单个 AWS 账户中的不同环境(开发、QA、演示等)上部署 AWS Lambda + API Gateway

javascript - .split() 不是函数错误

javascript - postman 回复 : Could not get any response from server

javascript - JWT 解码适用于 React Native 但不适用于 React

amazon-web-services - Lambda 尝试启动 ec2 实例时出现访问问题

amazon-web-services - Cloudfront - 重叠备用域名

amazon-web-services - 使用 Google 登录时无法取回 Cognito JWT token