passing header in axios error: 400 bad request - javascript

I am trying authorization to my react app using axios and that request works with postman but when I start react it gives me 400 bad request error
let user = JSON.parse(localStorage.getItem("user"));
let userName = user.userName;
let accessToken = user.accessToken;
console.log(accessToken);
let config = {
headers: {
'Authorization': 'Bearer ' + accessToken
}
}
console.log(config);
axios.post("http://localhost:8080/getUserType",config).then((response) => {
var res=response.data;
this.setState({loginValue:res.userType});
console.log(res.userType);
}).catch((err) => {
console.log(err);
})
}
console return this
Dashboard.js:32 Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)

Maybe try to directly use the headers instead of encapsulating them in a config variable.
let user = JSON.parse(localStorage.getItem("user"));
let userName = user.userName;
let accessToken = user.accessToken;
console.log(accessToken);
let headers: {
'Authorization': 'Bearer ' + accessToken
};
console.log(config);
axios.post("http://localhost:8080/getUserType", { headers }).then((response) => {
var res=response.data;
this.setState({loginValue:res.userType});
console.log(res.userType);
}).catch((err) => {
console.log(err);
})
}

Related

Pusher Beam beamsClient.setUserId always gets {"error":"Unauthorized","description":"Invalid JWT signature"}

I am implementing Pusher Beam Notification in our application and I always get a 401 error response when calling beamsClient.setUserId. I can verify that the JWT token generated is correct. Any idea why?
Here is the code I'm using:
const token = "****";
const instanceId = "****";
const currentUserId = "****";
const beamsTokenProvider = new PusherPushNotifications.TokenProvider({
url: "https://our-domain/pusher-beam-auth/",
headers: {
"Authorization": "Token " + token,
"Content-Type": "application/json"
}
});
const beamsClient = new PusherPushNotifications.Client({
instanceId: instanceId,
});
beamsClient
.start()
.then(() => beamsClient.setUserId(currentUserId, beamsTokenProvider)) // I always get 401 error here
.catch(console.error);
This answer only as per docs.
const currentUserId = "****";
const token = "****";
const instanceId = "****";
const tokenProvider = new PusherPushNotifications.TokenProvider({
url: 'https://our-domain/pusher-beam-auth/',
headers: {
Authorization: 'Token ' + token,
'Content-Type': 'application/json',
},
});
PusherPushNotifications.init({
instanceId: instanceId,
})
.then(beamsClient => beamsClient.start())
.then(beamsClient => beamsClient.setUserId(currentUserId, tokenProvider))
.then(() => console.log('Successfully authenticated with Pusher Beams'))
.catch(console.error);

Express.js can't find token from header

I have a problem in my authentication.js file where for some reason it can't access the token from the header but I have checked that I passed it on the front end. I also used postman and everything seems to work fine so I am sure that the problem is in the authentication.js file where when I try to console.log the token it's undefined.Below is the code:
const token = localStorage.getItem("token");
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
const token = req.get("authorization");
console.log(token); // Logs the token as undefined
if (!token || token === "") {
req.isAuth = false;
return next();
}
try {
let decoded = jwt.verify(token, process.env.JWT_SECRET);
req.duser = decoded.user;
res.status(200).send("Access granted.");
} catch (error) {
return res.status(403).send("Token is not valid.");
}
req.isAuth = true;
return next();
};
Also here is how I call the API:
const token = localStorage.getItem("token");
const { data } = await axios.post(
"/messages",
{
headers: {
Authorization: token
},
}
);
Please change this
headers: { Authorization: token },
to this
headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
in your api call
Do not forget to add data param as the second param. It's your request body.
axios
.post(
`/messages`,
data,
{
headers: {
"Authorization": `Bearer ${token}`, //mind the space before your token
"Content-Type": "application/json"
}
}
);
e.x. data
{
"firstname": "Firat",
"lastname": "Keler"
}
And then in the backend, check your token like that
const token = req.headers.authorization.split(' ')[1];
if (!token) {
//your logic
}
may be that your token isnt a Base64 String via client-side. Hope this helps
const temp = localStorage.getItem("token");
const token = Buffer.from(tmp, 'utf8').toString('base64')
axios.post('/messages', {
headers: {
'Authorization': `Basic ${token}`
}
});
RESOURCE:
https://flaviocopes.com/axios-send-authorization-header/

Can't authorize user in jwt - Node.js react.js

When user login , it should redirects to homepage and gets posts.
I make api call in react but it returns 401 unauthorized . If I do with same auth header on postman it returns proper data.
const getPosts = async () => {
await axios
.get("/api/post", {
headers: { authorization: "Bearer" + localStorage.getItem("token") },
})
.then((res) => setPosts(res.data));};
useEffect(() => {getPosts();},[]);
Server Side
router.get("/api/post", authToken, async (req: Request, res: Response) => {
const posts = await Post.find({ relations: ["user"] });
return res.json(posts);
});
middleware
const authToken = (req: Request, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, "SECRET", (err, decode) => {
if (err) return res.sendStatus(403);
res.locals = { ...res.locals, token: decode };
next();
});
};
You are missing the whitespace in your headers:
headers: { authorization: "Bearer " + localStorage.getItem("token") }

Getting net::ERR_ABORTED 401 in my react app

Below is my react code snippet. I have verified that the token is correct using postman. Does anyone have ideas what might be missing here ?
export async function getData() {
const url = buildUri();
const auth = "Bearer " + await getAccessToken(); // api call to get access token
console.log("Using auth: ", auth);
var res = fetch(url, {
method: 'GET',
mode: 'no-cors',
headers: {
"Content-Type": "application/json",
"Authorization": auth
}
}).then(response => {
return response.json();
}).catch((error) => {
console.log("Error getting data: ", error);
});
console.log('got res: ', res);
}

Can not download file while sending request from one node.js server to another

I am facing some issue while downloading file using node.js. I have scenario like my angular component is sending the file request. in my first node server I am doing the token validation and then redirecting to another node server where actually the execution happens. I am explaining my code below.
service.ts:
submitAndDownloadFile(formdata : any ){
const token = localStorage.getItem('token')
let headers = new HttpHeaders({
Authorization: 'Basic ' + token
})
const cecID = localStorage.getItem('cec');
const AppUrl = `${environment.nodeJsBaseUrl}:${environment.hostingNodeJsContainerPort}/convert-test-cases/${cecID}`;
return this.httpClient.post(AppUrl, formdata, { responseType: 'blob', observe : 'response', headers : headers});
}
Here I am sending the request to my first node.js server which code has given below.
app.js(first:port-8000):
router.post('/convert-test-cases/:id', middleware.auth, (req, res) => {
try{
let postRequestOptions = {
url: '',
method: 'POST',
json: true,
headers: {},
body: {},
};
postRequestOptions.url = 'http:localhost:9000/convert-test-cases';
postRequestOptions.headers = {
'Content-Type': 'application/json',
};
postRequestOptions.body = req.body;
request(postRequestOptions, async (error, response, pathList) => {
if(error) {
console.log('error', error);
}else{
res.send(pathList);
}
})
}catch(e){
responseObj = {
status: 'error',
msg: 'Error occurred while processing your request',
body: null
}
return res.send(responseObj);
}
})
Here I am doing the token validation using middleware.auth and sending same request to another node.js file which code is explained below.
app.js:(second-port-9000):
router.post('/convert-test-cases', async (req, res) => {
try{
let response = await ctcCtrl.convertTestCase(req.body, req.files);
if(response.status == 'success'){
res.set('Access-Control-Expose-Headers','*, Content-Disposition');
return res.download(response.fileName,response.fileName);
}else{
return res.send(response);
}
}catch(e){
responseObj = {
status: 'error',
msg: 'Error occurred while processing your request',
body: null
}
return res.send(responseObj);
}
})
Here only I am doing some execution and downloading the file. If I am connecting angular to node-9000 its working fine but my requirement is first I have to connect to port-8000 to some token validation and after that I have to send same req.body and re.file to app.js which is running in 9000 using request module. As per my code its not working at all.

Categories

Resources