I am facing a specific issue with making a post call using Angular js, the below code fails with error:
Response for preflight has invalid HTTP status code 404
How ever if I make the same call by passing parameters in plain text format, by appending values directly in URL it works. Any help here is appreciated.
eg: https://sample.com/services/srest/restserver/v1.0/authenticate/login?username=rakesh&password=somepassword
angular.module("sampleApp2",[])
.service("apiCalls",function($http) {
var result;
var postdata = {username: "rakesh", Password: "somepassword"} ;
this.cobLogin = function(callback,errcallback) {
result = $http({
method:'POST',
data:postdata,
url:'https://sample.com/services/srest/restserver/v1.0/authenticate/login'
}).then(callback, errcallback);
}
return result;
});
Provide headers
angular.module("sampleApp2",[])
.service("apiCalls",function($http) {
var result;
var postdata = {username: "rakesh", Password: "somepassword"} ;
this.cobLogin = function(callback,errcallback) {
result = $http({
method:'POST',
url:'https://sample.com/services/srest/restserver/v1.0/authenticate/login',
data:postdata,
headers: { 'Content-Type':'application/json'}
}).then(callback, errcallback);
}
return result;
});
It sounds like you are using the wrong content type. The default is Content-type: application/x-www-form-urlencoded. You want Content-type: application/json. You can set this in the headers option. Check the $http docs
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/json'
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
Related
I'm trying to make a get request with some params to a Spring get method. I'm using angular to make a call and this is my example
var apiUrl = 'api/trupci-filter';
var req = {
method: 'GET',
url: apiUrl,
headers: {
'Content-Type': "application/x-www-form-urlencoded" or "application/json"
},
data: {
klasa: "1",
promjer:"1",
duzina: "1"
}
}
console.log(req)
return $http(req)
And this is my get method in Spring:
#GetMapping("/trupci-filter")
#Timed
public ResponseEntity<List<Trupci>> getTrupciWithFilter(
#RequestParam(value = "klasa", required = false) String klasa,
#RequestParam(value = "promjer", required = false) String promjer,
#RequestParam(value = "duzina", required = false) String duzina )
The call is successful but the params are always null. I can't find any solution to this simple thing and I'm losing my mind.
Can anybody help me?
HTTP GET request can't have data element, its for request body like for HTTP POST, PUT etc. Please use params for query string parameters.
var req = {
method: 'GET',
url: apiUrl,
params: {
klasa: "1",
promjer:"1",
duzina: "1"
}
}
I've written the following script:
function uploadImageToDiscord() {
var link = "https://i.imgur.com/image.jpg";
var img = UrlFetchApp.fetch(link).getBlob();
var discordUrl = "https://discordapp.com/api/webhooks/mywebhook";
var payload = {
"file": img
};
var params = {
headers: {
"Content-Type": "multipart/form-data"
},
method: "post",
payload: payload,
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(discordUrl, params);
Logger.log(response.getContentText());
}
However, GAS tells me that I'm trying to send an empty message. Can anyone help me?
Error Message
The error must be related to either the way of me trying to download the image:
var img = UrlFetchApp.fetch(link).getBlob();
or the way of how I define the payload for the multipart/form-data content:
var payload = {
"file": img
};
How about this modification?
Modified script:
From:
var params = {
headers: {
"Content-Type": "multipart/form-data"
},
method: "post",
payload: payload,
muteHttpExceptions: true
};
To:
var params = {
method: "post",
payload: payload,
muteHttpExceptions: true
};
Additional information:
For example, if you want to add the text to the file, please use the following request body.
var payload = {
content: "sample text", // Added
file: img
};
var params = {
method: "post",
payload: payload,
muteHttpExceptions: true
};
Reference:
Webhook Resource
In my environment, I am using such request body. And it works fine. But if in your environment, it didn't work, please tell me. I would like to think of other solutions.
Angular Code:
getAuthorizationStatus: function () {
var deferred = $q.defer();
$http({
method: "POST",
url: url,
data: {
username: $scope.username,
password: $scope.password
},
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
},
My Server side code:
[HttpPost]
public int ValidateUser([FromBody]Credentials credentials)
{
try
{
string username = credentials.username;
string password = credentials.password;
//Do stuff
}
catch (Exception ex)
{
throw ex;
return -1;
}
return -1; // not valid user
}
The problem I am having is I am able to hit the Api Method but the data inside is always null. I have tried several combinations like this:
data: JSON.stringify({
"username" : "username",
"password":"mypassword"
}),
No dice.
What am I doing in wrong ?
Enclose your data in $.param()
Example :
data: $.param({ username: $scope.username,password: $scope.password })
I would instead trying to change the default and appropriate behavior of $http's POST, instead let the server read the data from the right place. Taken from MVC controller : get JSON object from HTTP body?:
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
It turns out that MVC doesn't really bind the POST body to any
particular class. Nor can you just fetch the POST body as a param of
the ActionResult (suggested in another answer). Fair enough. You need
to fetch it from the request stream yourself and process it.
Using [FromBody] beside the action input param is enough to get the data from request. Your problem is that you override the content-type in your Angular code through headers:
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //*** Remove this!
}
It must be 'application/json' in order to send json data. Just remove that headers and it should work normally.
I'm trying to send HTTP request using the following code:
var editCompanyUrl = 'http://X.X.X.X:YYYY/editCompany';
var userId = localStorage.getItem("UserId");
var token = localStorage.getItem("Token");
var companyId = localStorage.getItem("companyId");
return $http({
method: 'POST',
url: editCompanyUrl,
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and handler of the request on the server side accepts requests with Content-Type: multipart/form-data. How can I add this content type to the request? I've tried many advices and tips from tutorials but no success. Could you please help me? In addition to it - what should I do when I will add a file with an image to this request? Can I just add it as additional parameter of the request?
Thank you very much!
Angular POST must be like below code.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
it should have data:{ }
so try to put your params: inside the data and it should work.
I am new to Angular JS. I am writing a simple client to pull data from a HTTP endpoint.
All headers I set are sent over the wire under the header Access-Control-Request-Headers, but not as actual HTTP headers in the request.
delete $http.defaults.headers.common['X-Requested-With'];
var config = {
headers: {
'customHeader1': 'value1'
}
};
$http.defaults.headers.get = {
'customHeader2': 'value2'
};
$http.get("http://localhost:8280/abc",config).success(function(data) {
// alert(data);
$scope.names = data.records;
}).error(function(response, data, status, header) {
alert(status);
});
Could you try that suggestion from the official Angular JS documentation:
To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, Use the headers property, setting the desired header to undefined. For example:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});