没有Express的节点中间件 [英] Node Middleware Without Express

查看:98
本文介绍了没有Express的节点中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建与API Gateway集成的AWS Lambda服务器,但无法公开该服务器,因此无法将其挂接到Express中.我想知道是否有人知道在不使用Express的情况下使用中间件的最佳实践.

I'm building an AWS Lambda Server to Integrate with API Gateway and I'm unable to expose the server so that I can hook it into Express. I'm wondering if anyone knows a best practice for using middleware without 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类似的功能,在其中可以编写类似的内容,服务器将知道在该目录中搜索我的路线.

I want to have something similar to Express where I can write something like this and the server will know to search that directory for my routes.

server.use('/api', require('./api'))

推荐答案

由于您想要的是使用express进行API Gateway的本地模拟,因此这是我在项目中使用的.

Since what you want is a local simulation of API Gateway using express, here's what I'm using for my projects.

这不需要serverlessclaudiajs.

我也总是只使用Lambda代理集成,因此更简单.

I also always just use Lambda Proxy integration so it's simpler.

类似这样的事情...

Something like this...

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运行它,以便它监视文件并根据需要重新加载.

Then, run it with nodemon so it watches the files and reloads as necessary.

nodemon --watch '{src,scripts}/**/*.js' scripts/server.js

这篇关于没有Express的节点中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆