【发布时间】:2021-01-17 01:11:51
【问题描述】:
我的代码,我是 Express 的新手。
app.get('/', (req, res) => {
const name = req.query.name;
const rank = req.query.rank;
const headers = Object.entries(req.headers)
.map(([key, value]) => `${key}: ${value}`);
res.json({ success: true, data : { name, rank } , headers : headers });
});
server = app.listen(3000);
const res = axios.get('http://localhost:3000?name=John Malone&rank=Captain');
console.log(res);
终端输出
Promise { <pending> }
我改变了我的代码,数据输出
data: {
success: true,
data: { name: 'John Malone', rank: 'Captain' },
headers: [
'accept: application/json, text/plain, */*',
'user-agent: axios/0.20.0',
'host: localhost:3000',
'connection: close'
]
}
}
axios.get('http://localhost:3000?name=John Malone&rank=Captain')
.then(function(data) {
console.log(data.data.name); // Data response from server
});
显示未定义。
【问题讨论】:
-
因为
axios.get()返回了一个承诺。所以,当你console.log()它是返回值时,这就是你得到的——一个承诺。使用.then()或await从该承诺中获取已解决的值。 -
因为 axios.get 返回一个承诺。
标签: javascript node.js express