Search code examples
node.jsexpressexpress-router

Express route returning 404 error


The express route in my node app is returning a 404 error. It works locally but on the production server it returns a 404 error (bear in mind that I changed the AJAX url to the one on my production server before uploading). My code:

server.js:

const path = require('path');
const http = require('http');
const express = require('express');

const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;

var app = express();
var server = http.createServer(app);

app.use(express.static(publicPath));

app.post('/active-screens', function(req, res) {
  res.send('route works!');
});

server.listen(port, () => {
  console.log(`Server is up on port ${port}`);
});

index.js:

function checkRoute(){
  $.ajax({
    url: "http://localhost:8080/active-screens",
    type: "POST"
  })
  .success(function(data){
    console.log(data);
  });
}

checkRoute();

Solution

  • It was a CORS issue as pointed out by @WejdDAGHFOUS.

    I updated my server.js to this:

    const path = require('path');
    const http = require('http');
    const express = require('express');
    const cors = require('cors');
    
    const publicPath = path.join(__dirname, '/../public');
    const port = process.env.PORT || 8080;
    
    var app = express();
    var server = http.createServer(app);
    
    app.use(express.static(publicPath));
    
    app.post('/active-screens', cors(), function(req, res) {
      res.send('route works!');
    });
    
    server.listen(port, () => {
      console.log(`Server is up on port ${port}`);
    });