Can't send auth headers with axios - reactjs

Can't send authorization header with rest API. Got 'OPTIONS' error with status 0. All headers and options are allowed on the server. Server is written on PHP.
Here is my request:
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData},{
headers:{ 'Content-Type':'multipart/form-data',
Authorization:`Bearer ${token}`}
})
It seems like it does not send the header when there is authorization. However, it works, if i delete authorization, and leave only content type

This should do the trick
axios({
method: 'POST',
url:`${API_URL}users/${23}/profile/main/update`,
headers: {
'Content-Type':'multipart/form-data',
'Authorization':`Bearer ${token}`},
data: formData
})
Refer docs for browser

Try to send as below:
var headers = {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData}, headers)
Try using Ajax call below:
import $ from 'jquery';
$.ajax({
url:`${API_URL}users/${23}/profile/main/update`,
processData: false,
contentType: false,
data : formData,
method : "POST",
headers: {
"Authorization": `Bearer ${token}`
}
});

I had this same issue, it is possible that you are not passing the sent auth header from your apache config to your php application.
you might need to set
WSGIPassAuthorization On
inside your virtualhost config.
Check this

Related

Convert this CURL Command to Javascript fetch()

I have a problem, I'm trying to access an API via javascript fetch().
In their documentation, they only have the curl guide
curl https://test.com/form/{form_id}/data \
-u apikey:'some-key'
Can you guys help me convert it to javascript fetch?
I tested the code below but the browser console says error 401 now I don't think I did put the apikey on the right location.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
apikey : 'some-ley',
'Content-Type': 'application/json'
}
})
Thanks in advance. :)
I think what is failing there is the type of header you are sending in fetch.
The -u option in curl translates to the "authorization" header in fetch. So it would be something like this.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
'authorization' : 'Basic apikey:some-key',
'Content-Type': 'application/json'
}
})
Although probably you would need to base64 encode the apikey:some-key portion before sending it.
Try this format:
fetch("https://test.com/form/{form_id}/data", {
headers: {
Authorization: "apikey ABCDEFGHIJK.."
}
})
Try these awesome online cURL converters!
Here is the output when you paste the cURL command and select the Javascript target:
fetch('https://test.com/form/371489/data', {
headers: {
'Authorization': 'Basic ' + btoa('apikey:some-key')
}
});

What is the best way to enable CORS in React Application?

There are different ways to make a REST call in react-
e.g
axios.post('link', JSON.stringify(data1),
{
headers: {"content-type" : "application/json", "Access-Control-Allow-Origin" : "*"}})
.then(response => {
console.log("res:", response)
})
.catch(err =>{
console.log(err)
})
}
OR
fetch('http://localhost:8080/feedbacks/addfeedback', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
body:body
What is the most effiecient way to enable CORS.
Is there any other way that I can do this either in frontend or backend?
It depends on what HTTP library you are using.
See What is difference between Axios and Fetch?.
I usually use Axios, next what i do is creating a global instance and configuring Axios once.
export const api = axios.create({
baseURL: '_URL_',
timeout: 1000,
withCredentials: false,
responseType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // whatever you want
}
});
// You can add common headers later
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Also i'm enabling CORS on my server side application.
Thanks to #henrik123 for good explanation:
The browser is going to see that some Javascript request has tried to initiate a request to a different domain, subdomain or port than what the browsers is currently at. If any of these things are different, the CORS kicks in. Doesn't matter if you use Axios, Fetch or any other other library

Making an axios POST request with multipart/form-data, via React Native Debugger

I am trying to upload a file from React Native to my server. However I am unable to set the 'Content-Type' header to multipart/form-data.
Here's my simple request:
axios({
uri: 'http://localhost:3000',
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
});
I am using the React Native Debugger to monitor Network requests.
When I see my Network request inside the Debugger, I see this:
'Content-Type': 'text/plain;charset=UTF-8'
and the Request Payload is simply [object Object]
User Agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) ReactNativeDebugger/0.7.13 Chrome/58.0.3029.110 Electron/1.7.9 Safari/537.36
If I am unable to do this with the React Native Debugger, can anyone suggest any steps to testing via Expo.
Using the latest version of Axios (0.17.1), you make an HTTP request with 'Content-Type': 'multipart/form-data' in the header as follows:
const formData = new FormData();
formData.append('action', 'ADD');
formData.append('param', 0);
formData.append('secondParam', 0);
formData.append('file', new Blob(['test payload'], {
type: 'text/csv',
}));
axios({
url: 'http://localhost:5000/api/hello',
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
});
Two things: I am using url, not uri. Also, please insert your own form data and url. Inspecting the request, which has been replied successfully, this is what I get for the request header:
After hours trying to make it work, I realized that a multipart/form-data needs a boundary that is generated dynamically depending on the amount of data that is being sent.
Here is the code that works for me:
const data = new FormData();
data.append('field_name', 'field_pictures');
data.append('files[file]', fs.createReadStream(filepath), filename);
const headers = {
'Content-Type': 'multipart/form-data',
'Authorization': 'here you can set your headers',
...data.getHeaders() // this line is the key
// you need to mix your headers with those generated by the form data
}
return axios.post(url, data, { headers });
You can do simply:
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data; boundary=someArbitraryUniqueString';
It will set your headers for sure. However, I have been struggling with form data in React Native for a day and without success. After some experimental aproaches, I found out that everything works without debugger. I don't know why but with debugger, I have been sending empty body to the server.
What's more I didn't need to set headers as it is your question in this post.
According to #JMA answer,
import axios from 'axios';
export async function somefunction(data) {
const formData = new FormData(); // No imports needed
for(let key in userData) {
formData.append(key.toString(), data[key].toString())
}
return axios.post(`${ROUTE}`, formData, {
'Content-Type': 'multipart/form-data',
});
}
where: data is your payload to what you want to send. somefunction is function that send POST request to ROUTE.

How to handle CORS requests in AngularJS

I'm facing problem with CORS requests in AngularJS while calling web services but the same service able to call by using jQuery.
Note: From server side we are receiving header "Access-Control-Allow-Origin:*" and these services are running fine in jQuery application.
Here I'm posting my AngularJS code as well as jQuery code.
AngularJS:
$http({
method: 'POST',
url: $rootScope.host + "UserLogin",
//headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
"uname": $scope.uname,
"password": $scope.password
},
}).then(function (success) {
$scope.loginDetails = success;
console.log($scope.loginDetails);
}),function (error){
console.log(error);
});
If I pass the header like headers: { 'Content-Type': 'application/x-www-form-urlencoded' } able to ping the service but my request is not going in JSON format.
If I change the header to 'Content-Type': 'application/json', getting
XMLHttpRequest cannot load https://XXXX.XXXX.in/XXXXAPI/UserLogin.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://170.11.0.61' is therefore not allowed access.
I don't know what is the reason for this error.
$.ajax({
url: BASE_URL + "UserLogin",
type: "POST",
xhrFields: {withCredentials: true},
data: {
"uname": uname,
"password": password
},
cache: false,
success: function (result, textStatus, request) {
console.log(result);
},
error: function (e) {
console.log("Error in login service call:"+JSON.stringify(e));
}
});
This jQuery is sending my request in the json format.
Try to pass headers like
headers: { 'Content-Type': 'application/json' }

Http request in angular send undefine values

** It turns out that the problem was at the server **
I'm trying to excute HTTP post request (from my angular client) to my server (node express). The server recive the request but the data is undefined.
Already tried to make this req by postman and it worked perfect there.
var req = {
method: 'POST',
url: _url +'/login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: { user: 'someUser', password :'somePass' }
}
$http(req)
.then(function success(res){
...
}, function error(res){
...
});
You are sending JSON data and sending the header of x-www-form-urlencoded.
Change the content type to "application/json"
Like:
headers: {
'Content-Type': 'application/json'
}

Resources