简体   繁体   English

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

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

I have a server.js in my Droplet(server), I have a POST method here, I'm trying to check if the coming string matches with a spesific string.我的 Droplet(服务器)中有一个server.js ,我在这里有一个 POST 方法,我正在尝试检查即将到来的字符串是否与特定字符串匹配。

server.js服务器.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)

And here is the file I sent requests.这是我发送请求的文件。

request.js请求.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)
    })

The problem is, it always goes to the second IF statement, I can see the incoming string in second IF statement (the part response.write) and it always matches in the first one "token".问题是,它总是转到第二个 IF 语句,我可以在第二个 IF 语句(部分 response.write)中看到传入的字符串,它总是在第一个“令牌”中匹配。 I did even check the types of the strings, but somehow it always goes to the second IF statement.我什至检查了字符串的类型,但不知何故,它总是转到第二个 IF 语句。

Am I missing something here?我在这里错过了什么吗? Why it doesn't match the string even though the strings are the same and the first IF statement doesn't work?为什么即使字符串相同并且第一个 IF 语句不起作用,它也不匹配字符串?

You need to place your body.includes checks inside your request.on callback.您需要将body.includes检查放在request.on回调中。 JavaScript is asynchronous, so your callback will be executed aftyer your if statements are evaluated. JavaScript 是异步的,因此您的回调将在评估您的 if 语句后执行。

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

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