Node.js - "TypeError - res.setHeader is not a function"
Node.js - "TypeError - res.setHeader is not a function"
我正在尝试将 JSON 从 URL 加载到变量并将其发送回客户端的 javascript
var getJSON =require('get-json');
app.post('/json', function(req, res) {
getJSON(url, function(err, res){
if(err)
{
console.log(err);
}
else
{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify({json: res.result}));
}
});
});
每次我 运行 代码服务器都说 res.setHeader
不是一个函数,其余的都会中断。
post
和 getJSON
回调具有相同的 res
变量名。
试试这个:
var getJSON =require('get-json');
app.post('/json', function(req, res) {
getJSON(url, function(err, response){
if(err)
{
console.log(err);
}
else
{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify({json: response.result}));
}
});
});
对我来说,这是在我建立的论坛中获取数据时发生的。我在这篇博文中找到了解决方法:
https://dev.to/shailesh6363/facing-error-res-setheader-not-a-function-2oc9
我根据评论中的 atul singh 添加了代码。
app.js
的变化
app.use((res, next) => {
....
});
到
app.use((req, res, next) => {
....
});
现在应用程序不会崩溃,并且会成功获取并显示数据
我正在尝试将 JSON 从 URL 加载到变量并将其发送回客户端的 javascript
var getJSON =require('get-json');
app.post('/json', function(req, res) {
getJSON(url, function(err, res){
if(err)
{
console.log(err);
}
else
{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify({json: res.result}));
}
});
});
每次我 运行 代码服务器都说 res.setHeader
不是一个函数,其余的都会中断。
post
和 getJSON
回调具有相同的 res
变量名。
试试这个:
var getJSON =require('get-json');
app.post('/json', function(req, res) {
getJSON(url, function(err, response){
if(err)
{
console.log(err);
}
else
{
res.setHeader('content-type', 'application/json');
res.send(JSON.stringify({json: response.result}));
}
});
});
对我来说,这是在我建立的论坛中获取数据时发生的。我在这篇博文中找到了解决方法: https://dev.to/shailesh6363/facing-error-res-setheader-not-a-function-2oc9
我根据评论中的 atul singh 添加了代码。
app.js
的变化app.use((res, next) => {
....
});
到
app.use((req, res, next) => {
....
});
现在应用程序不会崩溃,并且会成功获取并显示数据