Javascript 获取axios返回未定义的请求
我正在尝试使用以下命令执行get请求:Javascript 获取axios返回未定义的请求,javascript,http,typescript,asynchronous,Javascript,Http,Typescript,Asynchronous,我正在尝试使用以下命令执行get请求: router.get('/marketUpdates',((request, response) => { console.log("market updates"); var data: Order[] axios.get('http://localhost:8082/marketUpdates') .then(function (response) { console.log("GET Response") con
router.get('/marketUpdates',((request, response) => {
console.log("market updates");
var data: Order[]
axios.get('http://localhost:8082/marketUpdates')
.then(function (response) {
console.log("GET Response")
console.log(response.data);
data = response.data;
})
.catch(function (error) {
console.log("Error in fetching market updates");
});
console.log("Data before sending is ")
console.log(data);
response.send(data);
}))
但是,底部的my console.log在console.log登录之前执行
数据在发送时未定义。有人知道我如何避免这种情况吗
then
中的数据与您要发送的数据不同。。。您使用的是函数(响应)
而不是arrow func(response)=>{}
因此,您正在绑定另一个李>
试着这样做:
router.get('/marketUpdates',((request, response) => {
console.log("market updates");
let data: Order[]
console.log("Data before sending is ")
console.log(data);
axios.get('http://localhost:8082/marketUpdates')
.then((getResponse) => {
console.log("GET Response")
console.log(getResponse.data);
data = getResponse.data;
response.send(data);
})
.catch(function (error) {
console.log("Error while fetching market updates");
});
}))
发送到服务器的请求总是异步的。这意味着,当服务器响应时,将执行函数.then()
让我重新格式化您的代码:
router.get('/marketUpdates',((request, response) => {
console.log("market updates");
var data: Order[];
console.log("Data before sending is ")
console.log(data);
axios.get('http://localhost:8082/marketUpdates')
.then((response) => {
console.log("GET Response")
console.log(response.data);
data = response.data;
response.send(data);
})
.catch(function (error) {
console.log("Error in fetching market updates");
});
}))
使用行axios.get('http://localhost:8082/marketUpdates“)
您正在触发对服务器的请求,服务器将做出响应,但这需要时间。当程序等待服务器响应时,JavaScript不会停止执行函数以保持用户界面运行
因此,.get
返回一个Promise,其中包含在不同场景中调用的多个函数。作为的第一个参数指定的函数。然后
将在服务器返回200和响应后立即调用
这意味着,只要axios触发对服务器的调用,代码底部的日志就会立即执行。此时没有数据,因为服务器尚未做出反应 代码是异步的,因此在请求等待响应时,将执行请求下面的所有代码。您只需将日志从底部移动到axios。Get加载https://localhost:8082/marketUpdates
url直接进入浏览器,查看它是否真的返回了您期望的内容。可能问题出在该页面上,而不是您在此处列出的snipper。此外,请检查response
本身的值(而不是response.data
)。它真的有数据
属性吗?只需移动响应。将(数据)
发送到中,然后
几乎同时回调2个类似的答案:)