[英]Receive Axios response from POST
在发出 Axios POST 请求后,我试图从我的 Node/Express 服务器接收响应。
我能够成功地向我的服务器发送一条消息,它在控制台中登录。 但是,我希望能够使用 response.send() 服务器端将一些数据返回到我的浏览器。
为什么 axios.post.then() 不在控制台中记录此响应?
- 客户端 -
<html>
<head>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<button onclick="axiosPost()">Post Test</button>
<script>
function axiosPost() {
axios.post('http://localhost:3000/submitMessage', {
message: "sample message",
}).then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
</script>
</div>
</body>
</html>
- 服务器端 -
const express = require('express');
const app = express();
const port = 3000;
var path = require('path');
// serves index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'))
});
app.listen(port, () => console.log(`Listening at http://localhost:${port}`))
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.post('/submitMessage', function(request, response){
message = request.body.message;
console.log("Message: " + message);
response.send('Server response message!!');
})
在您的前端收听response.data
。 或者在服务器端使用简单response.end('Message')
好吧我从来没有使用过Axios,但我认为你需要返回JSON
app.post('/submitMessage', (request, response) => {
message = request.body.message;
console.log("Message: " + message);
response.status(200).json({
status: 200,
ok: true,
data: {
msg: message
// Any data for the response
}
})
})
你也可以在前端使用 Async/Await
这里有一个不错的帖子,您可以查看它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.