Fetch 401 Authorization issue - reactjs

I've started to build a project using WooComeerce and React.js, but I have one question.
When I try to get the data, for example: "products", received an issue 401 unauthorized..
I've tested my request into Postman/Insomnia and everything is working as expected. I think the problem is coming from the headers part, but for now I can't handle the issue..
Also my response headers are empty!
Here is my code:
const getProducts = async () => {
const response = await fetch(`${process.env.REACT_APP_API_URL}products?consumer_key=${process.env.REACT_APP_API_CONSUMER_KEY}&${process.env.REACT_APP_CONSUMER_SECRED_KEY}`,
{
method: "GET",
mode: "cors",
credentials: "include",
headers: {
"Authorization": `Basic ${process.env.REACT_APP_API_CONSUMER_KEY}`,
"Content-Type": "application/json",
},
}
);
return response;
};
How can i fix that issue?
Note: I'm not using WooCommerce REST API package.
Thank you in advance!

Usually the basic auth string is base64-encoded string username:password. However i see the consumer key being used in the req and the header. Can you please double check your authorization header?

Related

How to make get request using axios by the following code

I faced, Refused to set unsafe header "User-Agent" issue while trying to make get request using woocommerce rest api v3. I want to make get request by using axios modifying the header. So How to do this using this code below from axios?
const woocommerce = new WooCommerceRestApi({
url: process.env.REACT_APP_WP_URL,
consumerKey: process.env.REACT_APP_WP_KEY,
consumerSecret: process.env.REACT_APP_WP_SECRET,
version: 'wc/v3',
axiosConfig: {
headers: {},
},
})
Try adding "Content-Type": "application/json;charset=UTF-8" to the headers like so:
const api = new WooCommerceRestApi({
url: url,
consumerKey: consumerKey,
consumerSecret: consumerSecret,
version: "wc/v3",
axiosConfig:{
headers:{
"Content-Type": "application/json;charset=UTF-8"
}
}
});

React JS CORS-ORIGIN - Instagram Basic Display API

I have problem with CORS: Access-Control-Allow-Origin when try to exchange the code for access token from Instagram API.
Instagram API documentation Step 5 : https://developers.facebook.com/docs/instagram-basic-display-api/getting-started#step-5--exchange-the-code-for-a-token
Body parametars:
const body = {
'client_id': 'xxxxxxxxxxxxxx',
'client_secret': 'xxxxxxxxxxxxxx',
'grant_type': 'authorization_code',
'redirect_uri': 'https://localhost:3000/',
'code': instaCode
};
My request:
axios.post(`https://api.instagram.com/oauth/access_token`, qs.stringify(body), {
headers: {'content-type': 'application/x-www-form-urlencoded'}
});
Đ¢his code worked 2 months ago.
edit: you can try this axios post request to send form data first which seems better, below worked for me though
That won't work, you have to send the body in a form data.
I believe fetch API would work but that's available since node 17, if you're using earlier version this is what worked for me.
SOURCE https://www.section.io/engineering-education/integrating-instagram-basic-display-api/
const { post } = require("request");
const { promisify } = require("util");
const postAsync = promisify(post);
const form = {
client_id: NUMBER,
client_secret: STRING,
grant_type: "authorization_code",
redirect_uri: STRING,
code: req.body.code,
};
let { body, statusCode } = await postAsync({
// let result = await postAsync({
url: "https://api.instagram.com/oauth/access_token",
form,
headers: {
"content-type": "multipart/form-data",
host: "api.instagram.com",
},
});
npm i request
and use that inside a try/catch of course

Post request in redux-saga not working, nothing seems to happen

I would like to make post request in redux-saga. My code looks like:
var formdata = new FormData();
formdata.append("points", "a,b");
formdata.append("pid", "someid");
formdata.append("tions", "cses");
formdata.append("exp", "cx");
const ans = yield call(fetch,
'http://localhost:8000/api',
{
method: "POST",
headers: { 'Authorization': 'Token tokenid',
"Content-Type": "application/json",},
body : formdata
});
In Postman it is working fine (selected form-data in body), but in saga, the POST request is not happening at all.
Please suggest where I am doing wrong?
The problem is with your Exceptions on server-side, When you are throwing an error the headers are not set. So what you should do is with CORS Errors only with 400 bad request react fetch request.
Update :- The 400 Bad request has gone away after I added "Content-Type": "application/x-www-form-urlencoded" in the headers and changed the body type accordingly
Example :-
fetch("api/xxx", {
body: "email=test#example.com&password=pw",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "post",
}

PostMan vs Axios on Including authorization Header while Making requests

Making a postman request to an endpoint with some Header
when I run the below code
function authenticateToken(req,res,next){
const bearerHeader = req.headers["authorization"]
console.log(req.headers)
if(typeof bearerHeader !== 'undefined'){
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
}
else{
console.log('hihihi')
res.sendStatus(403);
}
}//a middleware function used for JWT
it's returning everything as I expected like below
but the problem is, I need to connect it with my react. So I am making Axios request but it's not working
I tried giving headers using interceptors like below
axios.interceptors.request.use(
config=>{
config.headers.authorization = `Bearer ${token}`
return config
},
error =>{
return Promise.reject(error)
return error
}
)
axios.post("http://localhost:3000/stockdata/post",{
// some data
})
I also tried giving like below
axios.post(url,{data},{headers:{
'authorization': "Bearer "+ token,
'Accept': 'application/json',
'Content-Type': 'application/json'
})
i also tried with 'Authorization': "Bearer "+ token and without quotes Authorization: "Bearer "+token and also tried one time by removing Accept and content-type . but this is what am getting
The problem is only with the Axios request, not any other thing. what's going wrong in it?
I think when you tried with axios, there will be two requests as it has CORS issue. This issue comes if the client host is different from server host.
The first request is type OPTIONS to know whether to allow the POST or not and second request is actual POST.
What you are seeing might be of request type OPTIONS. This you can verify by checking network tab in the browser. This won't happen in POSTMAN. You could add CORS plugin to your server to resolve this issue.
The attached screenshot shows POSTMAN sending request to http://localhost:3000/stockdata/post
However, the axios request is being sent to http://localhost:3000/stockdata
Adjusting the request end-point may help resolve the issue.
After adjusting the target URL, the following code example may be tried to get the axios response:
import axios from 'axios'
let url = "http://localhost:3000/stockdata/post"
let data = {}
let token = "xyz"
let config = {"headers": {
"Authorization": "Bearer " + token,
"content-type": "application/json"
}
}
axios.post(url, data, config)
.then((response) => {
console.log(response)
}, (error) => {
console.log(error)
}
)
More information:
https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/

Reactjs POST request using axios [duplicate]

This question already has answers here:
Why is an OPTIONS request sent and can I disable it?
(15 answers)
Closed 4 years ago.
I am trying to call a POST request in ReactJs using Axios, but getting an error. Code:
const payload =
{
device_id: 'ASDACCAS',
device_type: 'Web',
device_version: '1.2',
device_user_id: 'ASDBADKKK1234AS'
}
axios({
method: 'post',
url: 'https://stageapi.myapi.com/v3_2/user/splash',
data: payload,
headers: {
'secret-key': 'mysecretkey',
'Content-Type': 'application/json'
},
})
But this is giving me error:
Failed to load https://stageapi.myapi.com/v3_2/user/splash: Response for preflight does not have HTTP ok status.
Kindly help me whats wrong here. I am new to ReactJS and moving from mobile app development environment. I have been on this for so long, tried every method for axios POST including by appending formdata to body. Still the same.
EDIT:
Also, I am not sure if its something related to CORS. I have installed the the CORS plugin in chrome. Are there any changes that I need to make in API side code? Which is written in php.
When you want to make a post request, you need to stringify body request like this:
axios({
method: 'post',
url: 'https://stageapi.myapi.com/v3_2/user/splash',
data: JSON.stringify(payload),
headers: {
secret-key': 'mysecretkey',
'Content-Type': 'application/json'
},
})
axios.post('https://stageapi.myapi.com/v3_2/user/splash',
payload,
headers: {
'secret-key': 'mysecretkey',
'Content-Type': 'application/json'
}
})
.then((response) => {
console.log(response.data);
});

Resources