如何在每个router.put或router.post调用中包含标头?

时间:2019-07-17 19:26:22

标签: reactjs express http

我想在每个router.put或router.post调用中包含一个标头。当前,我有一个router.put调用,其中包含以下逻辑:

router.put('/', async (req, res, next) => {
    const { body } = req
    const { authorization } = req.headers
    const options = {
        url: `${request_url}/saveconfig/`,
        json: true,
        body: body,
        method: 'PUT',
        headers: {
            'authorization': authorization
        }
    }

    try {
        let response = await httpRequest(options)
        res.status(response.statusCode).send(response.body)
    } catch (error) {
        res.status(400).send(error)
    }
})

但是我还有大约50个想要包括authorization: authorization头的router.put或router.post调用。在React或其他方法中是否可以做到这一点,以便每个router.put或router.post都包含此标头?

1 个答案:

答案 0 :(得分:0)

正如我在评论中提到的,您可以利用router.use方法添加一个新的中间件函数,如果请求是options对象,它将在req对象上创建POST对象类型为PUTrouter.use(function(req, res, next) { if (req.method === "POST" || req.method === "PUT") { const { body } = req; const { authorization } = req.headers; req.options = { url: `${request_url}/saveconfig/`, json: true, body: body, method: "PUT", headers: { authorization: authorization } }; } next(); }); router.put("/", async (req, res, next) => { try { let response = await httpRequest(req.options); res.status(response.statusCode).send(response.body); } catch (error) { res.status(400).send(error); } }); 的类型。

使用您的示例,您可以执行以下操作:

private static String _(String key)
{
    return PTR.getResources ().getStringProperty (key);
}

文档: https://expressjs.com/en/5x/api.html#router.use https://expressjs.com/en/5x/api.html#req.method