In my project, I already have AngularJS service that inserts desired object using $http.post as follows:
function insertObject(object, callback) {
$http.post(apiUrl, object).success(function (data) {
"object" is set in corresponding AngularJS controller and sent to my service like:
objectServices.insertObject(object, function (data) {
According to this, "object" is sent through $http post request body. What I need, is to send one additional variable inside this $http request. Actually, this variable should be URL (route), with which the controller works.
I can't change this object structure (to attach new property to it, which would hold URL info etc.) because $http.post(apiUrl, object) matches corresponding backend API Controller method that takes exactly this object as parameter (this object is entity).
I tried something like this:
Declare variable that will hold URL info:
var url = window.location;
And attach it to $http.post header like:
$http.defaults.headers.common["currentUrl"]= url;
where "currentUrl" is supposed to be key and url is value.
Also tried something like:
$http.post(apiUrl, object, headers: { 'currentUrl': url })
and on backend side, inside corresponding API Controller HttpResponseMessage method tried to extract it from request header as:
Request.Headers.Single(x => x.Key == "currentUrl").ToString();
but it didn't work. Please, can someone explain how to send custom data inside http post request and tell me what wrong is with my try?
EDIT: Content of Request.Header on backend side is:
While attaching the variable:
$http.defaults.headers.post.currentUrl = url;
When making the call, you missed the braces:
$http.post(apiUrl, object, {headers: { 'currentUrl': url }})
Related
I need to add the default global variable to all my POST requests using Axios.
I'm able to add the parameter using interceptor like:
axios.interceptors.request.use((config) => {
config.params = config.params || {};
config.params['timezone_adjust'] = window.timezone_adjust;
return config;
});
But in this case the url looks like "{url}?timezone_adjust=0
However I want to include the timezone_adjust variable on the request data object instead. Is that possible?
If you want to make a "global" settings to all your POST requests you should prefer using headers instead of body payload
Why? different requests may have different body payload, yet they can share common headers set (it is more common than shared payload)
In that case you can use Global axios defaults
axios.defaults.headers.post['YOUR-COMMON-HEADER'] = 'HEADER-VALUE';
Then you should fetch your headers from request object in your backend
i have created one URL and given to the end-user so when user hit my URL from other module i want to fetch the the data from the request body and and after fetching the data i am passing these data to my service and then validating and getting the response from my service.
but when user click on my URL and passing the data in URL then
I am able to fetch the data from URL like this
ngOnInit() {
this.route.params
.subscribe((params : Params) => {
this.email=params['id'];
});
but I am not able to fetch the data from request body when the user hit my URL so that i can fetch the data from the body and pass it to my service.
I need to fetch the two parameters from the request body.
Please first understand that the code you show is not a request to an api so there is no body.
All you are doing here is looking at the current route that shows in the address bar (ie. the current page of your angular app). There is no request body to fetch data from, only the query string params you can see in the address bar.
In other words, this.route refers to the CURRENT route of your angular app showing in the browser.
If you want to call an API and get data then you need to create a service to do that. For example:
#Injectable()
export class StoriesService {
constructor(private http:Http,private constService :ConstantsService) { }
public getStories()
{
this.http
.get(this.constService.apiBaseUrl + "/Stories")
.subscribe ((data: Response) => console.log(data));
}
}
In this example data is the request body returned by the call to [apiBaseUrl]/stories.
I would advise reading this tutorial.
I am trying to do a simple API call that returns an array. I believe I am successfully making the call, but the data is in the form of a cors type response object and I can't figure out where the data actually is or how to access it.
var React = require('react');
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent', {
method: 'get'
}).then(function(data) {
console.log(data);
}).catch(function(error) {
console.log(error);
});
When I type the url into the browser, the first part of the array is like this:
[{"username":"sjames1958gm","img":"https://avatars.githubusercontent.com/u/4639625?v=3","alltime":4401,"recent":528,"lastUpdate":"2016-12-06T16:10:35.053Z"},{"username":"diomed","img":"https://avatars.githubusercontent.com/u/72777?v=3","alltime":1524,"recent":482,"lastUpdate":"2016-12-03T21:57:45.952Z"},
So I assumed that I could do data[0].username but data[0] is undefined.
The actual object return looks a little like this: Response {type:cors, url:, status:, proto, etc}
In my Angular app, I am sending a config object with an $http.delete request using the following method:
return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}]})
This appends the value of my data key to the body of the request as you can see in the picture below:
However, Angular seems to be setting the content-type as text/plain by default, and I need to be JSON.
How can I change the content type of this $http.delete request?
EDIT: I posted a screenshot with the wrong Network tab open (Response Headers instead of Request Headers) by mistake. Here is the correct version:
#charlietfl, thank you for pointing that out.
After some research I found out you can pass multiple options (such as Content-Type) within the config object that I was already passing, like so:
$http.delete('projects/' + id + '/activityTypes',
{data: activitiesToDelete, headers: {'Content-Type': 'application/json'}});
The above is working exactly as intended, so it is indeed possible to send a body with an $http.delete using Angular, and further customize the http request using that same config object.
From Angular's $http documentation:
data – {string|Object} – Data to be sent as the request message data.
headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the
return value of a function is null, the header will not be sent.
Functions accept a config object as an argument.
I'm trying to send just the array of my data to the server. I found this post discussing how to send an array, but I can't get it to work.
AngularJS: ngResource and array of object as params to URL
The problem I am having is my resource gets sent back to me as JSON like this
{
Results: []
}
So when I ask for my resources,
var collaboratorResource = api.CollaboratorList.get({Id: Id });
but then, if I try something like
collaboratorResource.$save($scope.collaborators);
When I look at firebug, it shows that my data is being sent as
{
Results: []
}
when in reality, I don't want to send the data as an object with the array as a Results property. I want to send it just as an array []. I need to do that since the api is legacy and expects that.
I've been trying to see if transformRequest works, like if I did
collaboratorResource.$save({data: $scope.collaborators, transformRequest: function (data, headers) { return data.results; }});
collaboratorResource.$save({}, $scope.collaborators);
collaboratorResource.$save($scope.collaborators);
But that doesn't seem to work either. Is this even possible? As an aside, if I use $http like this, it works:
$http({ method: "POST", data: $scope.collaborators, url: collaboratorUrl });
I'm just not sure how to use the $resource service properly since I'd prefer to wrap everything in $resource if possible and not have a hybrid of both if possible. Thanks.