I am following a tutorial on React JS Authentication using JWT and created a login form that consumes a JSON API, which generates a token upon entering the correct username and password. When I click the the submit button, I get a 404 error - not found (via Chrome console / network tab). However, when I test the API via postman (entering the username and password (JSON) into the body, a token is returned)
The login page calls a function from another file, which is use to authenticate the user and obtain the token. I am wondering if my fetch statement is setup correctly, this is what I have:
login method:
login(username, password) {
// Get a token from api server using the fetch api
return this.fetch(`${this.domain}/login`, {
method: 'POST',
body: JSON.stringify({
username,
password
})
}).then(res => {
this.setToken(res.token) // Setting the token in localStorage
return Promise.resolve(res);
})
}
...this is my fetch method:
fetch(url, options) {
// performs api calls sending the required authentication headers
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
// Setting Authorization header
// Authorization: Bearer xxxxxxx.xxxxxxxx.xxxxxx
if (this.loggedIn()) {
headers['Authorization'] = 'Bearer ' + this.getToken()
}
return fetch(url, {
headers,
...options
})
.then(this._checkStatus)
.then(response => response.json())
}
below, I posted URLs to the full code if that helps:
Login https://codepen.io/lkennedy009/pen/GdYOYe?editors=0010#0
AuthService https://codepen.io/lkennedy009/pen/xjyPMY
withAuth https://codepen.io/lkennedy009/pen/bMmYyd?editors=0010#0
...could I get some help as to what I'm doing wrong and/or if there is something I'm missing?