I am a newbiew to ReactJs, need to know different ways by which we can include Headers in our service Url before making a call.
I am aware of how we used to make GET/POST Calls in angular Js after including headers...
Similarly want to know different ways to define headers in React Js, below is the sample of my component where i am making a service call.
There is a service Url which has few headers defined on Server side, how to include those headers on our side ...Sorry cant disclose the headers, please help me with some dummy headers data
componentDidMount(){
fetch('serviceURL')
.then(res=>res.json())
.then(items=>{
this.setState({
items : items.contactNumber
});
})
}
You can do something like this:
const request = new Request('https://example.com/some-url', {
headers: new Headers({
'Content-Type': 'text/plain'
})
});
fetch(request).then(() => { /* handle response */ });
You can find more information about using Headers in the docs.
Related
I'm trying to send image file to my backend API. Last works fine with Postman. The problem is not with image, I'm not able to send any request with axios and form data, no meter I append image or not.
Everything works fine with fetch. It took time to understand, that fetch does not need any content type, and last generates automatically as multipart/form-data with right boundary.
As written axios should do same as fetch, but it does not generate or change its content-type. Passing header 'content-type' : 'multipart/form-data does not do the trick of course. When I do not set content type it just use application/json. I was not able to find anything like that in documentation. Everywhere its says, that axios should create content type header automatically.
My axios version is 0.18.0.
Here is code, it can't be more simple =)
axios
.post(url, payload)
#######UPDATE#######
It turned out the problem was with axios interceptor. If you don't use interceptors you won't get this problem. So when I created new instance and deleted all headers no interceptors where called that's why my code worked. But let me bring more details to help others avoid this pain. Interceptor has transformRequest function where this part of code exists
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
where setContentTypeIfUnset function is
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
So if your object has undefined headers you will also pass this situation. But in my case even after deleting all headers I must pass some header to my application. And on setting it interceptor calls that transfromRequest function which adds that header to my formdata request.
I hope in future releases axios will fix this issue.
#######OLD ANSWER#######
As I guessed, somehow axios in my project set its default value for header content type and even setting it as 'content-type' : undefined did not overwrite that value.
Here is solution
let axiosInstance = axios.create();
delete axiosInstance.defaults.headers;
Then use that instance.
Spent whole day to find this solution.
const formData = new FormData();
formData.append('image', image); // your image file
formData.append('description','this is optional description');
Axios.post(`your url`, {body:formData}, {
headers: {
'content-type': 'multipart/form-data'
}
})
Can you please try this code once ?
You can try like this:
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
I am building an Ionic app, and trying to set custom headers for every GET request I do on the app.
This is the CustomHeaderController
angular.module('myHeader',[])
.controller('headerCtrl',['customHeader',function(customHeader){
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'text/html;odata=verbose',
"X-Request-from" : "{{vm.data.os}}" }};
$http.get('http://localhost:8100, config); }])
At the moment when I inspect the page, I do not get any custom header, just the default one.
Any clues? Appreciate it! Cheers.
You need to use interceptor in this case with every http request.
Interceptor Details
Have been using $resource.save(object); to post my objects to the rest service but this time I don't want the object to be marshalled. I need it to be posted as text/plain.
Is there an easy way of doing this using angularJS?
Solved my problem.
Used the config parameters in the .save or .post functions to set the header content-types.
var config = {
headers : {
'Content-Type': 'text/plain'
}
};
$http.post(theURL, theBody, config)
I'm using angular and angular-resource version 1.1.5 and I'm using a $resource to make a request to a REST service. But it seems like the custom headers is not appended to the request. My definition is as below. Is there anything I did wrong?
myApp.factory('User', function($resource) {
var User = $resource('http://localhost\\:7017/mydomain/users/jack', { }, {
get: {
method: 'GET',
isArray: false,
headers: {'X-Requested-By':'abc'}
}
});
return User;
});
Read this to see how to configure default headers in one place: http://docs.angularjs.org/api/ng.$http
EDIT:
Your header must be included in Access-Control-Allow-Headers header in response to the OPTIONS request, which is sent automatically prior to your GET request.
You can modify the default headers inside the $httpProvider.
the headers are an object and separated intocommon, patch, post and put
so if you want to change the default for all your requests, just do a
$httpProvider.defaults.headers.put['Content-Type'] = 'application/json';
You have to call get method by using its name, i.e User.get(callback)
It seems that custom headers do not get sent when get method is called with User.query(callback)
I'm trying to make a request to an API service that has a dynamic 'authorization' header.
var domain = "http://www.externalapi.com",
actions = {
'login': {
method: 'POST'
},
'objects': {
method: 'GET',
headers: {
'Authorization': Request.getAuthHeader()
}
}
};
var requests = $resource(domain, {}, actions);
requests.objects();
Request is a service I've written that has a method that builds the auth header based on the api requirements, the has it returns is correct.
When looking at the request to domain, however, I see not 'Authorization' header...
I've also tried passing in a static string, still no header.
So the issue was my versions.
After updating Angular to 1.2.0rc1 I left my ngResource module at 1.0.8.
After updating both to 1.2.0rc1 (I assume 1.1.2 would work as well) I was able to assign headers from the actions object of $resource.