axios post request without body getting to the server without the headers - reactjs

the request getting to the server without the headers:
const res = await axios.post(`/api/follow/${props.match.url}`, {
headers: {
Authorization: `Bearer ${token}`,
userId: userId,
},
});
anyone knows why?

should just put null in the body place, and it works

Related

React-Axios Getting error 401 (Unauthorized) for PUT Method

I have gone through many posts and tested most of them but I still get this error.
It's interesting that I don't get this error for the get method. I get this error only for put method.
thanks to everyone
axios error 401 (Unauthorized)
axios
.put("/api/v1/Profile", {
fullName: userName,
gender: Number(userGender),
phoneNumber: userNumber,
headers: {
Accept: 'application/json',
"Content-Type": "application/json; charset=UTF-8",
Authorization: `Token ${userToken}`,
},
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
There is no error for the get method, but it gives an error for the put method
I tested it with Postman and it works without errors
There is something wrong with your Authorization header. You're using the right syntax (see MDN):
Authorization: <auth-scheme> <authorization-parameters>
Given userToken is your <authorization-parameters>. The problem comes from the <auth-scheme> for which you used Token: this is not a valid scheme according to the list maintained by IANA.
Hard to be sure without much information, but I guess what you want is:
Authorization: `Bearer ${userToken}`,
My problem was solved with this format:
axios({
method: 'put',
url: 'api/v1/Profile/',
data: {
fullName: userName,
gender: Number(userGender),
phoneNumber: '',
},
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Authorization: `Bearer ${userToken}`,
},
}).then((response) => {
console.log(response);
});

Axios GET request to Spotify API returning 401

I used the format provided in this spotify web api reference and an access token generated from there directly, but I keep getting a 401 error. What is going on?
const accessToken = 'string from https://developer.spotify.com/console/get-current-user-playlists/?limit=50&offset=0';
console.log(accessToken);
axios
.get(
'https://api.spotify.com/v1/me/playlists',
{ params: { limit: 50, offset: 0 } },
{
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + accessToken,
'Content-Type': 'application/json',
},
}
)
.then((data) => console.log(data))
.catch((err) => console.log(err));
Error:
GET https://api.spotify.com/v1/me/playlists?limit=50&offset=0 401
Figured it out. Post requests have a body in the second param and headers for the third param. Get requests, however, have only the second param for both the URL parameters and headers. So I just had to combine the 2 objects into one:
axios
.get(
'https://api.spotify.com/v1/me/playlists', {
params: { limit: 50, offset: 0 },
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + newAccessToken,
'Content-Type': 'application/json',
},
})
)
Figured it out. Post requests have a body in the second param and headers for the third param. Get requests, however, have only the second param for both the URL parameters and headers. So I just had to combine the 2 objects into one

React native fetch() 403 status

I have an API endpoint working good in postman with the bellow options
The above request can get 200 status and got a response. Now I am trying to implement the same API with React Native using fetch method.
fetch('https://example.com/api/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx'
},
body: {
"useremail": "testuser#example.com",
"userpassword": "123456"
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
}).catch((error) =>{
console.error(error);
});
The above code was not working and I am getting 403 status.
Have you tried this
The easy way to implement this is to use this attribute to your AndroidManifest.xml where you allow all http for all requests:
android:usesCleartextTraffic="true"
feel free for doubts
You are passing data without converting it to json will make problem here
fetch('https://example.com/api/user/login', {
method: 'POST',
credentials : 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx',
},
body: JSON.stringify({ // convert object to json
"useremail": "testuser#example.com",
"userpassword": "123456"
}) ,
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
}).catch((error) =>{
console.error(error);
});
HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that access to the requested (valid) URL by the client is Forbidden for some reason. The server understood the request, but will not fulfill it due to client related issues.
so for first step in your postman use a fake user password to see if you get 403 again ,
if you got, that means you have problem in your sending your react native data.
so you should focus on your sending request code then,
According to docs
you can post like this
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
be sure that you are sending your user pass correctly and not missing anything like misspellings
hope this helps you.

MIcrosoft API get Calendar Event description and show it appropriately

In my React project, I made an Axios call to populate a Calendar Event List taking data from Microsoft Outlook Calendar (using Microsoft API). The result is the following
As you can see only event description give me a problem. Indeed to show the event description it shows me an HTML string without the event detail.
I read that I have to put in the header of my request Content-type:text, but I tried and It doesn't work. How I can solve that? This is my Axios Request
getEvents(startDate, endDate, accessToken) {
const startDateString = startDate.toISOString();
const endDateString = endDate.toISOString();
axios.get(
`https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
).then(response => this.setEvents(response.data.value))
.catch((error) => {
console.error(error.response);
});
}
For that matter Prefer: outlook.body-content-type="text" header needs to be specified.
According to documentation:
To specify the desired format to be returned in the Body and
UniqueBody properties in a GET request, use the Prefer: outlook.body-content-type header:
Specify Prefer: outlook.body-content-type="text" to get a message body returned in text format.
Specify Prefer: outlook.body-content-type="html", or just skip the header, to return the message body in HTML format.
Example
getEvents(startDate, endDate, accessToken) {
const startDateString = startDate.toISOString();
const endDateString = endDate.toISOString();
return axios.get(
`https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
{
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Prefer' : 'outlook.body-content-type="text"'
}
}
);
}
You need to give axios a config object. Currently, you are using the get property, that is why your code doesn't work currently:
axios({
url: `https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-type": "text"
},
})
You can read more here: https://github.com/axios/axios

Setting authorization header in Fetch API

I have a Node/Express backend and I'm consuming the API with a React Client. I want to be able to set the authorization header after a user is signed up. This ensures that subsequent requests are sent with the authorization header.
I can see how it's done in Axios here and how to retrieve the authorization header in Fetch here
Is it possible to do this with Fetch API and how?
Thank you in advance.
var url = "https://yourUrl";
var bearer = 'Bearer ' + bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone', //it can be iPhone or your any other attribute
'Content-Type': 'application/json'
}
}).then(responseJson => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));
As far as I know, there's no way to use default options/headers with fetch. You can use this third party library to get it to work, or set up some default options that you then use with every request:
// defaultOptions.js
const defaultOptions = {
headers: {
'Authorization': getTokenFromStore(),
},
};
export default defaultOptions;
Then use the default options like:
import defaultOptions from './defaultOptions';
// With default options:
fetch('/auth', defaultOptions);
// With additional (non-default) options:
fetch('/auth', { ...defaultOptions, body: JSON.stringify(additionalData) });
You can pass headers as second parameter of fetch:
fetch(<your url>, {
headers: {
authorization: <whatever is needed here>
}
})
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`,
'Accept': 'application/json',
'Content-Type': 'multipart/form-data;
},
In my case, the problem was that the string I was setting as the Authorization was not yet generated. I had to wrap it in a promise, and suddenly it worked.
let authHeader: string = await SearchAuthService.getAuthHeader();

Resources