Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
ExpressJS does not seem to work with ajax calls

I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.

My ajax call:

$.ajax({ 
        method: "POST", 
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login", 
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {  
            alert('success');
        }
    });

In my express:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', function (req, res) {
  var user = req.body.user;
  var password = req.body.pass;
  if(user == 'john' && password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!');
});

Any help is greatly appreciated.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

you should return some response from your express code, also response should be ended especially in case of just sending only the status code like res.status(401);

app.post('/login', function (req, res) {
    var user = req.body.user;
    var password = req.body.pass;
    if(user == 'john' && password == '123') {
        res.status(200).json({t:1});
    } else {
        res.status(401);
    }

    res.end();
});
about 4 years ago · Santiago Trujillo Relatório

0

This work for me:

   $.ajax({
        type: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function (err) {
            console.log(err);
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });
    app.post('/login', function (req, res, next) {
    var user = req.body.user;
    var password = req.body.pass;
    if(user == 'john' && password == '123') {
    res.status(200).json({s: 1});
    } else {
    res.status(401).json({e: 2});
    }
   });
about 4 years ago · Santiago Trujillo Relatório

0

var json = JSON.stringify({user:"john", pass:"123"});

$.ajax({ 
    dataType: 'json',
    type: "POST", 
    url: "/login", 
    data: json
}).done(function(data){
    console.log("works fine");
});

Should work for an Ajax post function, sending the data to the node server. The url needs to match the url of the app.post in the node server file, you don't need localhost in front of it. ContentType is also not necessary and I made the json object outside of the Ajax call instead of setting it inside the Ajax call.

var express = require('express');
var parser = require('body-parser');

var app = express();

var port = 8000;

app.use(parser.urlencoded({extended: false}));
app.use(parser.json());
app.use(express.static('public'));

app.post('/login', function (req, res) {
    var user = req.body.user;
    var password = req.body.pass;

    if(user == "john" && password == "123") {
        res.status(200);
    } else {
        res.status(401);
    }
});

var server = app.listen(port, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("App listening at http://%s:%s", host, port);
});

And that should work for the node server itself. I set the server running, so you can always keep track of what port it's listening on, so you don't need to bother scrolling down to change the port, just change the port at the top of your file. Further the /login was looking fine to me. Also, I edited the app.use statements and added an extra one.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda