Reputation: 101
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.')
});
});
Upvotes: 1
Views: 1477
Reputation: 65
Remove the JSON.stringify here and try making a request
body: JSON.stringify({
"username": username,
"password": password
})
Upvotes: 0
Reputation: 1188
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!');
Upvotes: 1