繁体   English   中英

NodeJS POST请求正文字符串不匹配

[英]NodeJS POST Request body string doesn't match

我的 Droplet(服务器)中有一个server.js ,我在这里有一个 POST 方法,我正在尝试检查即将到来的字符串是否与特定字符串匹配。

服务器.js

const http = require('http')

const server = http.createServer(function(request, response) {

    var body = '';

    if (request.method === 'POST') {


        request.on('data', function (data) {
            body = data;
        })

        if (body.includes("token") === true){
            request.on('end', function () {

                response.writeHead(200,body);
                response.write(body);
                response.end('success');
            });

        }

        if (body.includes("token") === false){
            request.on('end', function () {

                response.writeHead(200);
                response.write(body);
                response.end('Not Auth. ')
            });
        }


}})

server.listen(3000)

这是我发送请求的文件。

请求.js

const axios = require('axios')

axios
    .post('SERVERIP', "token"
    )
    .then(res => {
        console.log(`statusCode: ${res.statusCode}`)
        console.log(res.data)
    })
    .catch(error => {
        console.error(error)
    })

问题是,它总是转到第二个 IF 语句,我可以在第二个 IF 语句(部分 response.write)中看到传入的字符串,它总是在第一个“令牌”中匹配。 我什至检查了字符串的类型,但不知何故,它总是转到第二个 IF 语句。

我在这里错过了什么吗? 为什么即使字符串相同并且第一个 IF 语句不起作用,它也不匹配字符串?

您需要将body.includes检查放在request.on回调中。 JavaScript 是异步的,因此您的回调将在评估您的 if 语句后执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM