0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.