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.')
});
});
http://192.168.0.106:3000/loginwas 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.const data = await response.text();, which will get you the plain text response from the server without JS trying to parse it. Also tryconsole.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.