Everytime i make a fetch request i get an error:
server running on 8000 port
{ type: 'https://httpstatus.es/401',
status: 401,
title: 'Unauthorized',
detail: 'Access token invalid or expired' }
I keep getting a new token and it still shows that error
this is my method, im not sure what im doing wrong
app.get('/', function (req, res) {
const token = {SOME LONG ASS TOKEN HERE};
fetch('https://api.petfinder.com/v2/animals?sort=random', {
headers: {
Authorization: `token ${token}`
}
})
.then(res => res.json())
.then(json => console.log(json));
})
it works on postman but not in my backend
im super confused lol
I got it to work
i changed token to Bearer on my authorization
so:
headers: {
Authorization: `Bearer ${token}`
}
Related
I am making a fetch (POST) request from client side to validate the login credentials if all is correct then I want to redirect user to welcome page.
But I am getting error Uncaught (in promise)
"SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON"
I am making a fetch (POST) request from client side to validate the
login credentials if all is correct then I want to redirect user to welcome page.
This is the router logic:
router
.route("/login")
.get((req, res) => {
res.render("auth/login");
})
.post(
authController.isUserExists,
authController.isPasswordCorrect,
(req, res) => {
res.render("welcome", { user: req.body });
}
);
Below is Fetch Request
form.addEventListener("submit", (e) => {
e.preventDefault();
fetch(url, {
method: "POST",
body: JSON.stringify({
email: email.value,
password: password.value,
}),
headers: {
"Content-type": "application/json",
},
})
.then((raw) => raw.json())
.then((result) => {
console.log(result.status);
alert(result.message);
})
.catch((err) => {
console.error(err);
});
});
I think error is being caused because promise is not being resolved.
Please take a look.
"SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON"
I am trying to authenticate a user through some API configured with passportjs. When I run the authentication request I get the redirect to the success route, but I can't get req.user. I tried through Postman and it works. I don't know what I'm forgetting. Could anyone help me?
This is my success route:
app.get("/success", async (req, res) => {
if (req.user){
return res.status(200).json({
user: req.user,
message: "Logged"
});
}
else {
return res.status(401).json({
message: "User authentication failed"
});
}
});
This is my react code:
const handleSubmit = (e) => {
e.preventDefault();
fetch("http://127.0.0.1:3001/login", {
method:"POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
redirect: "follow",
body: JSON.stringify({email: email, password: password})
}).then(resp => {
return resp.json();
}).then(data => console.log(data))
}
While you are calling the success/ route you need to add the authorization header along with the fetch request. We need to add the Basic jwt | authentication token as the authorization key
const response = await fetch(apiURL, {
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`,
// add the basic jwt | drf token for Authorization Key
},
body: JSON.stringify(yourNewData)
})
I'm banging my head against the wall trying to solve issuing a patch request after getting an access token. This same access token works for get requests to https://${appDomain}/api/v2/users/${userid}. But it fails with "Request failed with status code 401" when trying to use it to patch app_metadata.
Using NodeJS and Axios.
axios
.post(`https://${appDomain}/oauth/token`, {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
audience: `https://${appDomain}/api/v2/`,
})
.then(({ data: { access_token, token_type } }) => {
const jwt = jwtDecode(access_token)
axios
.patch(`https://${appDomain}/api/v2/users/${userid}`, {
data: {
app_metadata: { stripeCustomerId: customer.id },
},
headers: {
Authorization: `${token_type} ${access_token}`,
},
})
.then(({ data }) => {
console.warn('patch response', data)
})
.catch((err) => {
console.error('patch error', err) // <--- ERROR 401 happens here
res.send(err)
})
})
.catch((err) => {
console.error('token error', err)
res.send(err)
})
After shadow boxing documentation I discovered a syntax error in my axios.patch call. Format should have been the following, which fixed my problems. I was passing data:{...} when it should have been like this:
axios.patch(
`https://${appDomain}/api/v2/users/${userid}`,
{
app_metadata: { stripeCustomerId: customer.id },
},
{
headers: {
Authorization: `${token_type} ${access_token}`,
},
}
)
I wrote an API that do some stuff, and I protect this using a jwt token.
This is the function for check the validity (checkAuth):
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization;
const decoded = jwt.verify(token, process.env.TOKEN_SECRET);
req.userData = decoded;
next();
}
catch (error) {
return res.status(401).json({
message: 'Auth failed'
});
}
};
And I define the route of the API in this way:
router.post('/myAPI', checkAuth, MyAPIDefinition);
When I try to fetch the API, using an expired jwt I can't get the response of the checkAuth. This is my API call using await fetch:
const response = await fetch(`${API_URI_DEV}/myAPI`, {
method: 'POST',
body: JSON.stringify({encod: { content: data }}),
headers: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
'authorization': jwt
}
});
The content of response is undefined.
I am building Web application on my localhost.
The front-end is Reactjs framework, running in localhost:3000
The back-end is nodejs + Express, running in localhost:4000
Now, I have created the API below:
router.post('/register', function (req, res) {
console.log(req.body); // {}, why it is empty?
// create new instance, save it to database
User.create(req.body).then(function () {
res.send('success');
});
});
The front-end part is:
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values); // value is not empty, I have tested! So we did send something to the API
const input = JSON.stringify({
username: values.username,
password: values.password,
});
console.log(input);
$.ajax({
url: `${API_ROOT}/register`,
method: 'POST',
data: JSON.stringify({
username: values.username,
password: values.password,
}),
}).then((response) => {
if (response === 'success') {
this.props.history.push('/login');
} else {
console.log('do not jump');
}
});
}
});
}
I have tested the API by the postman, I can add users to MongoDB, so the API is good.
I have console.log what I sent to API, it is not empty, however, backend API receive d empty request body. I have already fixed the "Access-Control-Allow-Origin" issue, so I think I do send something to the API, but backend API received empty request body.
If you add a content type header saying what type the body of the request is it should work as expected.
$.ajax({
url: `${API_ROOT}/register`,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({
username: values.username,
password: values.password,
})
})