[英]res.send is not a function
我正在進行api調用並接收數據,但是,我無法將數據發送回我的js文件。 我嘗試使用res.send,但出現錯誤。 我似乎無法弄清楚如何將信息發送回javascript文件。 (我從請求鏈接中刪除了密鑰。但是出於安全原因,我從api調用中獲取了數據)。 我唯一的問題是將數據返回到前端javascript文件。
這是發送原始請求的Javascript文件:
/ ********** options button function makes api call to get selected cities forecast *****************
function getCityForecast(e){
var id = document.getElementById('cities');
var getValue = id.options[id.selectedIndex].value;
var suffix = getValue + ".json";
var newObj = JSON.stringify({link : suffix});
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(newObj);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
console.log(xhr.response);
console.log('recieved');
} else {
console.log('error');
}
}
}
我的server.js文件如下所示:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');
var request = require('request');
// ****************** Middle Ware *******************
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
var retrievedString;
// **************** Post Request *******************
app.post('/', function(req, res){
var link = "http://api.wunderground.com/api/key/forecast";
retrievedString = link.concat(req.body.link);
request = http.get(retrievedString , function(res){
var body = '';
res.on('data', function(data){
body += data;
});
res.on('end', function(){
var parsed = JSON.parse(body);
console.log(parsed.forecast.txt_forecast);
res.send(parsed.forecast.txt_forecast);
});
})
.on('error', function(e) {
console.log("Got error: " + e.message);
});
});
app.listen(3000, function() { console.log('listening')});
您正在超載變量res
的定義,這也稱為Express路由處理程序方法的響應變量。 在請求的回調函數中,對該變量使用其他名稱-例如:
request = http.get(retrievedString , function(resDoc){
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.