React Axios get call doesn't work with authorization header - reactjs

I am working on a Axios get in the react which need authorization.
Before I add the authorization, it worked well, and after I add the authorization header in the backend and frontend, it has CORS error. I tried the get call in the postman and it works very. So I think it shall be Axios get code in the frontend.
Here is Axios get code:
async sendGetRequest(variable) {
return new Promise((resolve, reject) => {
let AuthStr = 'token';
console.log(typeof(AuthStr)); => the type is String
Axios.get(`url/${variable}`,{
header:{
'Authorization': AuthStr
}
})
.then(res => {
resolve(res.data)
}
);
})
}
I am not sure it's wrong, looks good for me.
Here is my postman result.(I hide the url)

I closed this post by myself.
Because I made a typo mistake
it shall be
headers:{
'Authorization': AuthStr
}
Hope it will be helpful for others.

Related

Axios returns NetworkError / CORS Headers enabled

I build a ionic-react android application with Axios to get a server response. Two weeks ago my code was working fine. Now the axios request always returns a NETWORK_ERR (HttpError or Axios Error).
I tried to use all CORS Headers possible in my api, but the request is not sent to the webservice.
I hope anyone can help me:
This is the Code I was using:
const api = axios.create({
baseURL: "http://192.168.0.145:8080/RestFulTest-1.0-SNAPSHOT/api",
});
function callApi(){
api.get("/verification")
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
}
Just directly opening the API Url in browser is not loading it...
Sot it seems either the backend is down or blocking and requires an authorization header with the axios request, like
let tokenStr = "Your TOKEN";
axios.get("/verification", { headers: {"Authorization" : `Bearer ${tokenStr}`} });
Hope it helps..

Axios post blocked by CORS. Using CLoudinary api

I am trying to do a post request with axios to upload a image to cloudinary from my frontend React app. I am getting this error from the axios code below:
http://localhost:3000 has been blocked by CORS policy: Request header field x-access-token is not allowed by Access-Control-Allow-Headers in preflight response.
Using axios, doesnt work gives me cors error
await axios({
method: "POST",
url: "https://api.cloudinary.com/v1_1/******/image/upload/",
data: {
file: img,
upload_preset: "*****",
cloud_name: "****",
},
})
.then((res) => {
console.log("response");
console.log(res);
})
.catch((err) => console.log(err));
Meanwhile when i use fetch using the same api request, the post request works and doesnt give me error. Anyone know why and how to call the api using axios?
const data = new FormData();
data.append("file", img);
data.append("upload_preset", "*****");
data.append("cloud_name", "*****");
await fetch(
" https://api.cloudinary.com/v1_1/****/image/upload/",
{
method: "post",
body: data,
}
)
.then((resp) => resp.json())
.then((data) => {
setUrlArray((prevState) => [...prevState, data.url]);
})
.catch((err) => console.log(err));
Extra info: My upload preset is unsigned.
Also got this from the console after making the axios api call
{
error: {
message: "Upload preset must be specified when using unsigned upload"
}
}
To create an Axios request equivalent to your working fetch() one, you need to
Craft a FormData instance and set it as the request data so your content-type is multipart/form-data
Make sure you're not using a previously created Axios instance with unwanted default headers
If custom headers have been set on the default Axios instance, eg
axios.defaults.headers.common["x-access-token"] = TOKEN
you may need to override / delete them in transformRequest
To avoid any interceptors defined on the default Axios instance, create a new separate instance for un-intercepted requests
import axios from "axios" // import the default instance
// create a new instance without interceptors.
// you could also create this in its own module and import from there
const instance = axios.create()
const data = new FormData()
data.append("file", img);
data.append("upload_preset", "*****");
data.append("cloud_name", "*****");
const res = await instance.post(
"https://api.cloudinary.com/v1_1/******/image/upload/",
data
)
Ideally, if your app is going to customise requests, you should always use an Axios instance (or multiple instances) to avoid messing around with the defaults.

How to use axios PUT method in React when there is authentication required?

Like the title says, I need to use PUT method with axios in react, but also I need to have authentication. I am using this api: https://gorest.co.in/ , and on the site as you can see for PUT mehtod, you are required to use access token which can be provided to you when you login onto the site. Now, I have done that, and I got my token, but somehow I still get 401 status code a.k.a I am unauthorized for PUT method, here is what I have done:
const [data, setData] = useState(null);
useEffect(() => {
axios
.put(
"https://gorest.co.in/public/v1/users/6",
{
name: "Test",
body: "This is an updated user",
},
{
headers: {
Authorization:
"my token, for privacy reasons I am deleting it, but it goes here",
},
}
)
.then((response) => {
setData(response.data);
});
});
This is my first time doing PUT method so I am really confused on what I am doing wrong here. If someone could help me, I would appreciate that.
Do you have the word Bearer before your token?
Like:
Authorization: Bearer <auth-token>
How about this?
{
headers: {
Authorization: `Bearer ${myToken}`,
},
}
The website defines the header like this
Authorization: Bearer ACCESS-TOKEN

How to implement slack Oauth-2.0 in react js?

I need to implement slack authorization in my project for sending message in channel,Direct message and add reminder .So can anyone suggest me how to implement slack authorization in react project or is there any npm package that i can utilize to implement slack authorization like google authorization.
I had the this problem. Took me ages to solve but anyway here is my solution:
useEffect(() => {
const getdata = async (con) =>{
try{
await axios.get("https://slack.com/api/users.identity",con).then((res) => console.log(res)).catch((err) => console.log(err))
}
catch{
}
}
const gettoken = async () => {
try{
await axios.get("https://slack.com/api/oauth.v2.access",{params: {client_id: sclientId, client_secret: sclientsecret, code: name1[1]}}).then((res) => setData(res.data.authed_user.access_token)).catch((err) => console.log(err));
}catch
{
}
}
gettoken();
const config = {
headers: {
"Access-Control-Allow-Headers": "authorization",
"Access-Control-Allow-Origin": "*",
"Authorization": `Bearer ${ data}`,
"token": data
},
};
getdata(config);
})
so sclientid,sclientsecret, and name1(which stores code) were variables I defined in my code. I had a link(or button) that redirects the user to slack for authorization . code below:
<a href ={`https://slack.com/oauth/v2/authorize?user_scope=identity.basic,identity.email,identity.avatar&client_id=${sclientId}`} ><img src="https://api.slack.com/img/sign_in_with_slack.png" /></a>
after the user has given permission then he is directed back to my site with a code. i used window.location.search to get the code out of the url and store it in name1[1] and then using that my gettoken function sends the client_id,client_secret and code to slack with a get request. this brings back json which includes the token. I then send this token back to slack as a header in a request using my getdata function which returns the user info. To get the client_id ,client_secret and set the redirect url you have to go to apps.slack.com and create an app. Ask me any questions if this is not clear enough

"Network Error" with Axios and DjangoREST but request succeeds at the end

So, I am using ReactJS and DjangoRESTframework to build my app.
Now..when I send a request with Postman it works perfectly(ex. 127.0.0.1:8000/api/users/ GET request) and when I try to do it in React with Axios I get a network error but on my local development server console I see that it succeeded.
This is my get request with axios in react:
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/users/', {
headers: {
'Accept': 'application/json'
}
})
.then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})
}
And I get an Network Error. But as I said with Postman it works.
One more example is that I send POST request with Axios to http://127.0.0.1:8000/api/users/ and as response I get Network Error as well but on my backend, user IS created.
This is code for my POST request with axios:
let formData = new FormData();
formData.set('email', this.state.emailField);
formData.set('username', this.state.usernameField);
formData.set('password', this.state.passwordField);
axios({
method: 'POST',
data: formData,
url: 'http://127.0.0.1:8000/api/users/',
config: {headers: {'Content-Type': 'multipart/form-data'}}
}).then(request => {
console.log(request.data);
}).catch(err => {
console.log(err);
})
I googled for about an hour to fix this but nothing helps.
Can you be more clear on what you see as Network error? Attach some error messages / Stack trace.
This looks like a Cross-Origin Resource Sharing (CORS)
issue to me. Try configuring CORS on your DjangoRESTframework backend.
This might help you if that is the case.

Resources