如何设置路由的头和参数.进入Node js?



如何设置路由的头和参数。进入节点js?我想把头值和参数设置为API数据调用URL。

router.get("/getdata", async (req, res) => {
res.header({
'key': '123456'
});
await fetch(`https://example.com/api?param=${data}`)
.then((data) => data.json())
.then((data) => res.json({ msg: data }))
.catch((err) => console.log(err));
});

我的问题是如何设置报头和参数数据在路由器。Get in node js

问题不清楚,你应该添加更多的细节,并询问可能导致问题的具体事情。

在响应上设置报头,可以直接在res对象上完成,像这样:

res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})

查看更多详细信息。

如果你需要在fetch API调用中设置header,你可以直接在fetch中这样做:

async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}

如果你想读取req对象中的参数:

router.get("/getdata", async (req, res) => {
const query = req.query // its an object containing all the params 
await fetch(`https://example.com/api?param=${data}`)
.then((data) => data.json())
.then((data) => res.json({ msg: data }))
.catch((err) => console.log(err));
});

阅读Express关于路由的文档。它解释了如何使用req.query来访问获取URL中的param

最新更新