GLHF
GLHF

Reputation: 4035

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.

server.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

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". I did even check the types of the strings, but somehow it always goes to the second IF statement.

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?

Upvotes: 0

Views: 110

Answers (1)

gear4
gear4

Reputation: 844

You need to place your body.includes checks inside your request.on callback. JavaScript is asynchronous, so your callback will be executed aftyer your if statements are evaluated.

Upvotes: 1

Related Questions