React Fetch Method return 415 - reactjs

I'm trying post request by my react app and I have return status 415. I tested this endpoint by postman exactly which I got from this console.log(JSON.stringify(data.data)); and all is right. I notice that my request haven't the same content-type which I set in fetch method.
fetch("http://localhost:8080/v1/useranswers", {
method: "POST",
mode: "no-cors",
headers: {
Accept: " */*",
"Content-Type": "application/json",
},
body: JSON.stringify(data.data),
}).then(function (response) {
return response;
});

I add line #CrossOrigin(origins = "*") in my controller and all is right :)

Related

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",
}

CORS post call not working in Angularjs

I am trying to implement cross-origin post call from angularjs application, then I get the following error.
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
But, when I make a Ajax call it works properly.
How HTTP post call work in angularjs?
Ajax call
$.ajax({
type: 'POST',
url: getAccessTokenUrl,
data: JSON.stringify(clintdata),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resultData) {
console.log(resultData);
},
error: function (request, status, error) {
console.log(status);
}
});
Angularjs HTTP call
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
'Authorization': undefined,
'Auth-Token': undefined
}
}).then(function(res){
console.log(res);
}, function(err){
console.log(err);
});
I have some default setting. Authorization is for others REST
$http.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8;' ;
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Access-Control-* headers are response headers. They come from the server in response to a request. You do not apply them to your request headers.
If your jQuery request works correctly without adding any additional headers, then your AngularJS request should work the same.
The equivalent jQuery request in AngularJS (including removing the Authorization and Auth-Token headers you've set via defaults) is
$http.post(getAccessTokenUrl, clientdata, {
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(response => {
console.log(response.data)
})
or the long version
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(...)
AngularJS by default...
POSTS requests as application/json content-type
Serializes the data property to JSON
Expects a JSON response
Resolves the $http promise with a response object with the response body parsed as JSON into the data property
Remove the following setting
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Add Authorization header dynamically from Interceptor
request: function(config) {
if (angular.isUndefined(config.skipInterceptor) || !config.skipInterceptor) {
// add Authorization token
}
return config;
}
Http call like this
$http.post('your url', {
skipInterceptor: true
})

Mailchimp api not working with fetch and Reactjs

I cannot get the fetch api to work with the mailchimp api in React. I'm also using webpack to run a devserver.
This is what I have:
componentDidMount() {
let authenticationString = btoa('123:myapikey-us17');
authenticationString = "Basic " + authenticationString;
fetch('https://us17.api.mailchimp.com/3.0/lists/fakelistid/segments', {
mode: 'no-cors',
method: 'GET',
credentials: 'same-origin',
headers: new Headers({
'Authorization': authenticationString,
'Accept': 'application/json',
'Content-Type': 'application/json'
})
}).then(function(e){
console.log("fetch finished")
}).catch(function(e){
console.log("fetch error");
})
}
I've tested the exact same api request in Postman and that works fine.
When I try this in React I keep getting a 401 status code saying "Your request did not include an API key."

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