0

I have a very simple user backend up and running (node, express, mongoose, mongo, etc) and with postman can verify when I add a user it works, when I request a login it works and get a token, and if I put in the wrong details it rejects it,

Now I used this git hub repo https://github.com/christiannwamba/vue-auth-vuex to spin up a simple frontend for this. Which I thought was all working fine as it appeared to be logging in until I found it was accepting whatever details I put in for the email and password as correct!

The backend server kept responding ok when I hit it with the vue app, but on closer inspection when I console logged what it was getting, which was null and returning user not found. So again I don't think there is anything wrong here.

Something I have noticed in chrome dev tools network, it is sending two versions of authenticate, first is empty and then the next one has responses.

I'm at a bit of a loss why it's sending empty requests first time and why it allows the login when it's getting a bad return.

Server.js file:

const express = require('express');
const logger = require('morgan');
const movies = require('./routes/movies') ;
const users = require('./routes/users');
const bodyParser = require('body-parser');
const mongoose = require('./config/database'); //database configuration
var jwt = require('jsonwebtoken');
var cors = require('cors')
const app = express();

// Add cors
app.use(cors());
app.options('*', cors());  // enable pre-flight

app.set('secretKey', 'nodeRestApi'); // jwt secret token

// connection to mongodb
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));

app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: false}));

app.get('/', function(req, res){
res.json({"api" : "User API"});
});

// public route
app.use('/users', users);

// private route
app.use('/movies', validateUser, movies);


app.get('/favicon.ico', function(req, res) {
    res.sendStatus(204);
});

function validateUser(req, res, next) {
  jwt.verify(req.headers['x-access-token'], req.app.get('secretKey'), function(err, decoded) {
    if (err) {
      res.json({status:"error", message: err.message, data:null});
    }else{
      // add user id to request
      req.body.userId = decoded.id;
      next();
    }
  });

}


// express doesn't consider not found 404 as an error so we need to handle 404 it explicitly
// handle 404 error
app.use(function(req, res, next) {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// handle errors
app.use(function(err, req, res, next) {
    console.log(err);

  if(err.status === 404)
    res.status(404).json({message: "Not found"});
  else  
    res.status(500).json({message: "Something looks wrong :( !!!"});

});

app.listen(3000, function(){
    console.log('Node server listening on port 3000');
});

Update:

I have added in under my CORS bit in server.js:

app.options('/users/authenticate', function(req, res){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'POST');
  res.end();
});

In network I now only get the one request. Under form data it appears to be there but it's saying in the response that data is null, and even more odd the vuejs is still logging in and allowing access to the restricted pages.

karl
  • 291
  • 1
  • 12
  • How are you parsing the request? Are you using `body-parser`? Seeing some code would help provide context to this issue. – glitch Sep 11 '19 at 17:04
  • Hi, body-parser yes, I have added my server.js file – karl Sep 12 '19 at 09:20
  • Add `app.use(bodyParser.json()) to your server.js` – glitch Sep 12 '19 at 10:42
  • Still null unfortunately, in the header request in vue I'm setting the content type to application/x-www-form-urlencoded – karl Sep 12 '19 at 10:49
  • Just to get clarification: Are you seeing the request on the server side that Vue is sending or does it show as empty? – glitch Sep 12 '19 at 10:52
  • Yeah in the terminal I see a request come through and when I console log the request and response it's null and user not found. – karl Sep 12 '19 at 10:58
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/199365/discussion-between-zer0kompression-and-karl). – glitch Sep 12 '19 at 11:02

2 Answers2

1

Temporarily comment out the line where you set the headers to application/x-www-form-urlencoded. Then add app.use(bodyParser.json()) to your server.js and see if it works. What's happening is your request object is malformed, which is why the server cannot parse the request correctly.

glitch
  • 266
  • 2
  • 8
0

Looks like CORS issue. If you run UI using a different server and your backend is running by itself, then your browser will send pre-flight request first which is an options request. That is the reason you see 2 authenticate requests in the developer tools. You can read more about this here Why is an OPTIONS request sent and can I disable it?

Gowthaman
  • 1,117
  • 1
  • 8
  • 13
  • Hi, I have app.use(cors()); app.options('*', cors()); which should sort this already? I was getting pre fligt warnings before this but they went away after, but is there more I need to do? – karl Sep 12 '19 at 09:15