我想在每个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都包含此标头?
答案 0 :(得分:0)
正如我在评论中提到的,您可以利用router.use
方法添加一个新的中间件函数,如果请求是options
对象,它将在req
对象上创建POST
对象类型为PUT
或router.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