[英]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.