1

I am sending post request to the server to validate my login data, but when I press login button it show this error:

[SyntaxError: JSON Parse error: Unrecognized token '<']

I console log response and I got this:

{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "b69da009-81d6-4391-adf6-99a76a7d5f55", "offset": 0, "size": 145}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "b69da009-81d6-4391-adf6-99a76a7d5f55", "offset": 0, "size": 145}}, "bodyUsed": false, "headers": {"map": {"connection": "keep-alive", "content-length": "145", "content-security-policy": "default-src 'none'", "content-type": "text/html; charset=utf-8", "date": "Fri, 01 Jan 2021 17:03:21 GMT", "keep-alive": "timeout=5", "x-content-type-options": "nosniff", "x-powered-by": "Express"}}, "ok": false, "status": 404, "statusText": undefined, "type": "default", "url": "http://192.168.0.106:3000/login"}

And when I console log the values that I input in the <TextInput it shows this:

[Sat Jan 02 2021 01:03:22.300]  LOG      undefined
[Sat Jan 02 2021 01:03:22.500]  LOG      undefined

Here is my code:

 constructor(props) {
    
    super(props);

    this.state = {
      isLoading: true,
      loggedIn: false,
      username: '',
      password: '',

    }
  }

  validateUser = async (username, password) => {
    try {
      const response = await fetch('http://192.168.0.106:3000/login', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          "username": username,
          "password": password
        })
      });
    
      console.log(response);
      const data = await response.json();
      await AsyncStorage.setItem('jwt', data.access_token);
      await this.props.navigation.navigate('adminD')
    } catch (e) {
      console.log(e);
    }
  };

And here the TextInput fields:

 <TextInput
                style={{ flex: 1 }}
                placeholder={'username'}
                onChangeText={(username) => this.setState({ username })}
                value={this.state.username}
              />
   <TextInput
                style={{ flex: 1 }}
                placeholder={'password'}
                onChangeText={(password) => this.setState({ password })}
                value={this.state.password}
                secureTextEntry={true}
                password={true}
              />

Code of server side:

app.post('/login', (req, res) => {
    const username = req.body.username;
    const SECRET_KEY = CONFIG.secret_key;

    findUserByUsername(username, (err, user) => {
        if (err) return res.status(500).send('Server error!');
        if (!user) return res.status(404).send('User not found!');
        const result = bcrypt.compareSync(req.body.password, user[0].password);
        if (!result) return res.status(401).send('Password not valid!');

        const expiresIn = 24 * 60 * 60;
        
        const payload = { id: user[0].id };
        const accessToken = jwt.sign(payload, SECRET_KEY, {
            expiresIn: expiresIn
        });
        // Check expiration date on the token.
        jwt.verify(accessToken, SECRET_KEY, (errs, data) => {
            console.log(errs, data);
        });
        // To fetch the data shown below, grab the key names.
        res.status(200).json({ "user": user, "access_token": accessToken, "expires_in": expiresIn });
        console.log('Succesful validation of the user.')
    });
});
15
  • The server doesn't respond with valid JSON. Commented Jan 1, 2021 at 18:14
  • @xehpuk and how to solve this Commented Jan 1, 2021 at 18:16
  • 1
    Analyze your server code. It looks like the server probably responds with HTML, a 404 Not Found error page precisely. Commented Jan 1, 2021 at 18:18
  • 1
    You'll need to do a little more debugging of the server. Looks like you got a 404 error which means that the resource http://192.168.0.106:3000/login was not found. Maybe it's an invalid path or set up incorrectly. Try accessing it from the command line with a tool like curl: curl -k -v -X POST http://192.168.0.106:3000/login -d '{"username":"username","password":"password"}' and see what you get back. Commented Jan 1, 2021 at 18:21
  • Simeon's suggestion is very good. If you don't have cURL, then you can also try const data = await response.text();, which will get you the plain text response from the server without JS trying to parse it. Also try console.log(response.status, response.statusText), which will tell you the HTTP response codes the server gave you. If you've also written the server code, a very common mistake is that you set up your login page with app.post('login') instead of app.post('/login'), or you set it up with app.get('/login') by mistake. Commented Jan 1, 2021 at 18:23

2 Answers 2

1

Thanks for posting the server code. I think the problem is that you're not responding with json at all. Change your response for the 404 (and others to this on the server side):

if (!user) return res.status(404).json(error: 'User not found!');
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for replying back,, i have tried your way and still same problem [Sat Jan 02 2021 02:53:07.490] LOG 404 undefined [Sat Jan 02 2021 02:53:07.780] LOG [SyntaxError: JSON Parse error: Unrecognized token '<']
The real problem is that server and client don't agree. Sending plain text for an error response is fine, as long as the client doesn't try to parse it as JSON.
0

Remove the JSON.stringify here and try making a request

body: JSON.stringify({
          "username": username,
          "password": password
        })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.