Node.js接口返回响应报错:res.send is not a function 求助
解决"res.send is not a function"错误
问题根源
你代码里的变量名冲突了:Express接口的回调参数是(request, response),但在调用第三方API的http.request回调中,你用了res作为参数——这个res是第三方天气API返回的响应对象,它属于Node.js原生http模块,没有Express框架提供的send方法。你真正需要用来给客户端返回响应的是外层的response参数。
修正后的后端代码
app.post("/weather", function(request, response) { let city = request.body.city; const options = { method: 'GET', hostname: 'open-weather13.p.rapidapi.com', port: null, path: "/city/" + city + "/EN", headers: { 'x-rapidapi-key': '-----', // 替换为你的实际密钥 'x-rapidapi-host': '-----' // 替换为实际host } }; // 将回调参数名改为apiRes,避免和Express的response冲突 const req = http.request(options, function (apiRes) { const chunks = []; apiRes.on('data', function (chunk) { chunks.push(chunk); }); apiRes.on('end', function () { const body = Buffer.concat(chunks); const weatherData = JSON.parse(body.toString()); // 使用Express的response对象返回数据给客户端 response.send(weatherData); }); // 处理第三方API响应的错误 apiRes.on('error', function(err) { response.status(500).send({ error: '获取天气数据失败', details: err.message }); }); }); // 处理http.request本身的错误 req.on('error', function(err) { response.status(500).send({ error: '请求第三方API失败', details: err.message }); }); req.end(); });
额外注意事项
- 确保你的Express应用已经配置了解析请求体的中间件,否则
request.body.city会是undefined:// 在app.post路由之前添加 app.use(express.urlencoded({ extended: true })); app.use(express.json()); - 前端AJAX的
url要和后端服务的端口、路由保持一致,当前代码里后端如果是8002端口则无需修改。
内容的提问来源于stack exchange,提问作者letsCode
相关产品推荐
相关产品推荐

