How to post a string to a rest service using angularJS - angularjs

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)

Related

React Js - Defining headers in the service

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.

How to set request part for POST request with angular-file-upload and Spring?

Unfortunately this answer does not help me. The problem appears to be that the request parameter file is not present in my POST request for some reason.
I am trying to upload a file, any file whether it's a binary file or a text file, in a POST request. The REST controller reveals:
#PostMapping(WordEmbeddingApiPaths.UPLOAD_MODEL)
#RequestMapping(method=RequestMethod.POST, headers={"Content-Type=multipart/form-data"})
public ResponseEntity<WordVectorListDto> uploadModel(
#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
LOGGER.debug("POST uploadModel");
return new ResponseEntity<WordVectorListDto>((WordVectorListDto)null, HttpStatus.OK);
}
and on the client I am running:
var uploader = $scope.uploader = new FileUploader({
url: 'http://localhost:8080/rest-api/dl4j/we/uploadModel'
});
uploader.onAfterAddingFile = function($modelFile) {
console.info('onAfterAddingFile', $modelFile);
var fd = new FormData();
fd.append('file', $modelFile.file);
$http.post($modelFile.url, fd, {
headers: {
'Content-Type': 'multipart/form-data'
},
params: {'file' : $modelFile.file}
})
.then(
function (data) {
alert("upload success");
},
function (data, status) {
alert("upload error");
}
);
};
However, I am getting 400 Bad Request as server response.
Any idea what the problem is?
Update:
I saw that an internal exception got thrown on the server side stating:
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present
I thought that I am setting this already - how can I make this right?
Posting FormData with AngularJS
When doing a POST with a FormData API object, it is important to set the Content-Type header to undefined.
var fd = new FormData();
fd.append('file', $modelFile.file);
$http.post($modelFile.url, fd, {
headers: {
//'Content-Type': 'multipart/form-data'
'Content-Type': undefined
},
//params: {'file' : $modelFile.file}
})
When the XHR send() method gets a FormData object created by the FormData API it automatically sets the content type to multipart/form-data and includes the proper boundary.
By having the AngularJS framework override the content type, the boundary is not set properly.
Debugging Small Programs
This question is an example of putting several things together without debugging each part.
This question has several unknown code components:
An undebugged AngularJS POST method
An undebugged Spring Backend
An undebugged mysterious AngularJS service
This answer pointed out errors with the AngularJS POST method but there are a couple of other unknowns. Is the Spring backend working properly? Is the mysterious FileUploader service being used correctly?
Debugging involves isolating unknowns and testing them separately.
Does the Angular POST method work with a known backend such as HTTP BIN - HTTP Request & Response Service?
Does the Spring backend work with an uploader that has been tested?
For more information, see How to debug small programs.
if you are using #EnableAutoConfiguration then you need to do the following as discussed here https://github.com/spring-projects/spring-boot/issues/2958
#EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
define the following beans
#Bean(name = "multipartResolver")
public CommonsMultipartResolver commonsMultipartResolver(){
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(50*1024*1024);
return resolver ;
}
#Bean
#Order(0)
public MultipartFilter multipartFilter(){
MultipartFilter multipartFilter = new MultipartFilter();
multipartFilter.setMultipartResolverBeanName("multipartResolver");
return multipartFilter;
}

Issue sending JSON in POST request to Play App

i am working on a project using Play Framework 2.4 using a simple Java template, as in many documentation i have seen, i just wrote a simple controller with my business methods and put the necessary paths on my route's file.
Now i am writing a client in Angular.js to invoke the logic written in the play app. It had work perfectly with GET methods, but when i try to do a POST from angular using the next lines:
$http({
method: 'POST',
url : rootURL + '/user/company',
data : {id : '123456' , name: 'xxxxxx'}
});
I receive a 404 Error. After several hours of forums searching, i found that the Play App is expecting application/x-www-form-urlencoded in the request content-type header.
So i modify my Angular call to the following:
$http({
method: 'POST',
url : rootURL + '/user/company',
data : {id : '123456' , name: 'xxxxx'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj){
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
})
};
And the POST works perfectly on this way, but i wonder, is there any way so i can make a POST request to my play app where the content-type is set to application/json? How can achieve this?
UPDATE
Here is my controller code:
public class MyController extends Controller {
public Result myAction(){
//do funny stuffs
}
}
And my route file has the following
POST /path/action controllers.MyController.myAction()
Have you added #BodyParser.Of(BodyParser.Json.class) in your action method?
Also when you are doing POST to a different domain, first check you request to see if it's a POST, I don't know about AngularJS, but with Polymer, it sent a OPTION first during ajax POST to different domain, and I met very similar issue (wrong content type and 404) which is resolved by implementing an OPTION on server which accept POST.
To Fix that, you need to manually implement an OPTION, here's what to do:
First, In your routes file, add an entry to accept OPTION
OPTIONS /*url controllers.Application.optionCheck(url)
Then implement the optionCheck method which accept everything
public Result optionCheck(String url){
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Access-Control-Allow-Methods", "POST");
response().setHeader("Access-Control-Allow-Headers", "accept, origin, Content-type, x-json, x-prototype-version, x-requested-with");
return ok();
}
And that's it

AngularJS $resource not sending custom headers

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)

ngResource Dynamic Header

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.

Resources