【问题标题】:Receive Axios response from POST从 POST 接收 Axios 响应
【发布时间】:2020-10-26 00:11:03
【问题描述】:

在发出 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!!');
})

【问题讨论】:

  • 您已经说过它没有在做什么,但它在做什么呢? then 回调会触发吗?或者是catch 吗?控制台中是否显示任何其他消息?
  • 然后根本不触发。控制台中唯一显示的是: Listening at localhost:3000 Message: sample message
  • 浏览器的控制台,而不是 Node 的。
  • 我之前没有检查过,但是是的,这是在浏览器控制台中:{data: "Server response message!!", status: 200, statusText: "OK", headers: {…} ,配置:{…},…}
  • 嗯,这就是响应对象,它正在记录它,那么问题是什么?

标签: javascript node.js post axios


【解决方案1】:

在您的前端收听response.data。或者在你的服务器端使用简单的response.end('Message')

【讨论】:

    【解决方案2】:

    嗯,我从来没有使用过 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

    有一个很好的帖子here你可以查看它

    【讨论】:

    • Axios 非常有能力处理纯文本响应。如果您发送的只是一个简单的字符串,则无需将其编码为 JSON。
    • 好的,但是管理客户端出现错误等不是更容易吗?
    • 并非如此。 HTTP 状态码可以表达错误状态。无论哪种方式,它都不能解决问题(结果是“OP正在查看错误的控制台”)
    猜你喜欢
    • 2019-12-30
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多