Wednesday 24 May 2017

Why does the browser return unexpected end of input when I can get the API response from browser?

I have a very basic react front end and a very basic nodejs server.

I'm trying to validate the username and password on the server when the client clicks submit and then eventually redirect them to their dashboard. Right now I am not able to go any further than sending the request for user data.

This is my very basic authentication function on the server, functions like authenticate and searchusers are not asynchronous.

// Authorization
app.get('/auth/:userId/:hash', function(req, res){
  var id = req.params.userId.toString();
  var hash = req.params.hash.toString();
  var error = {
    err: 'something went wrong!'
  }
  var user = dm.searchUser(id, users);
  if (!user){
    res.json(error);
  }
  var isAuthenticated = dm.authenticate(user, hash);
  if (!isAuthenticated){
    res.json(error);
  }
  if(isAuthenticated){
    console.log('authed')
    res.json(user);
  }
});

and this is my client side react component method that handles the submit action of a form.

  submit(e){
    e.preventDefault();
    const BASE_URL = "http://localhost:3001/auth/"
    fetch(`${BASE_URL}${this.state.userId}/${this.state.password}`, {
      method: 'GET',
      mode: 'no-cors'
    })
    .then(response=>response.json())
    .then(json=>{console.log(json)})
    .catch((err)=>{
      console.log(err)
    })
  }

From what I have tried, if I tried to send a request from my browser, the server does respond with my JSON data.

View browser output when requested directly to the API using browser

But when I try to do the same with my client, it gives back an error, can someone please help me out with what is going wrong?



via buoyantair

No comments:

Post a Comment