Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda