Making a simple POST call using Angular $HTTP service:
authService.login = function(username, password){
var credentials = 'username=' + username + '&' + 'password=' + password;
return $http({
method: 'POST',
url: href,
headers: {'accept': acceptValue, 'content-type': contentType},
data: credentials
}).then(onSuccess, onError);
};
Can't get the error status, instead I get SyntaxError: Unexpected token E.
the console first show the status 401 and immediately after the parse error.
wonder what it does under the hood, what is it trying to parse, and why I'm not able to get error.status to work.
The problem could be with how you are serializing your data. Rather than build the string yourself, you might try passing them directly into data as an object:
data: {username: username, password: password}
Angular should serialize the info in the data object by itself.
If that doesn't work, Angular also has a built-in alternative to its default serializer that mimics the one found in jQuery. Docs on it are here. Your request with this method would look something like:
$http({
url: "/auth/login",
method: "POST",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
data: $httpParamSerializerJQLike({
email: email,
password: password
})
})
If you go with this option, don't forget to inject $httpParamSerializerJQLike as a dependency.
It seems that you request is correctly sent and you receive the response.
I made a try with a RESTful service that returns an 401 status code. Here is my JavaScript code:
var href = 'https://contactsapi.apispark.net/v1/contacts/';
var acceptValue = 'application/json';
var contentType = 'application/json';
var credentials = {}; //'something';
function onSuccess(data, status, headers, config) {
}
function onError(data, status, headers, config) {
console.log('data = '+JSON.stringify(response, null, 2));
}
$http({
method: 'POST',
url: href,
headers: {'accept': acceptValue, 'content-type': contentType},
data: credentials
}).then(onSuccess, onError);
The response object contains in my case the following:
{
"data": {
"code": 401,
"contactEmail": null,
"description": "The request requires user authentication",
"homeRef": "/",
"reasonPhrase": "Unauthorized",
"uri": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2"
},
"status": 401,
"config": {
"method": "POST",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://localhost:8182/contacts/",
"headers": {
"accept": "application/json",
"content-type": "application/json"
},
"data": {}
},
"statusText": "Unauthorized"
}
What could help you is to have a look at the response content (headers / payload). For example, if the payload is a JSON one, the value of the Content-Type header. Perhaps there is a gap between the Content-Type of the response and the actual content. For example, you received from plain text content with content type value application/json.
I made a test to simulate such case (XML content with a content type application/json) and I have the following error:
SyntaxError: Unexpected token <
at Object.parse (native)
at vc (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:15:480)
at Zb (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:82:229)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:83:143
at m (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:7:322)
at dd (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:83:125)
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:84:380)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:119:113
at n.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:133:221)
at n.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:130:233)
Angular tries to parse JSON content but since it's malformed, it can't and throws an error.
It seems to be similar to your error. So I think the problem isn't in your Angular application but in the server...
Hope it helps you,
Thierry
Related
I'm trying to create a webhook via the GitHub API. The docs say that I need to provide a config parameter, which should be an object, but I'm not sure how I can send a JSON in the URL parameters. Here's what I've tried:
fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config={"url": "https://webhooks.example.com", "content_type": "json"}`, {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
}
});
and
fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config.url=https://webhooks.example.com&config.content_type=json`, {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
}
});
They both result in the following error:
{
"message": "Validation Failed",
"errors": [
{
"resource": "Hook",
"code": "custom",
"message": "Config must contain URL for webhooks"
}
],
"documentation_url": "https://developer.github.com/v3/repos/hooks/#create-a-hook"
}
How do I properly send a JSON object? I'm looking for a solution using node-fetch
When you are doing a post request, it's implied that there will be a payload and the lib you are using will be expecting a body property containing your payload.
So just add
fetch('https://api.github.com/repos/${repo.full_name}/hooks', {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
},
body:JSON.stringify(yourJSON) //here this is how you send your datas
});
And node-fetch will send your body with your request.
If you want more details on that i'll expand my answer
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods here for a quick description of different http request type (verb)
I'm trying to post data to my django rest framework using javascript fetch. I've already set up and liked the DRF to my model and got everything set up from the backend. I used the postman app to ensure "get", "post" etc are all working as interned. However, now I'm having problem posting data using javascript to post the data using fetch. I want to add data to my article model which has a "headline", "tag", "content", "background_image" and the user that posted the article.
This is how my code looks like
data = JSON.stringify({
headline: "Testing",
tag: "Testing",
background_image: "Testing",
content: "Testing",
user: 1
})
fetch(
"http://127.0.0.1:8000/api/v1/articlesapi/",
{
method: "post",
headers: {"Authorization":"Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e"},
body: data
}
).then(function(response) {
return response.json();
}).then(function(data) {
console.log("Data is ok", data);
}).catch(function(ex) {
console.log("parsing failed", ex);
})
However, I keep getting the error parsing failed TypeError: Failed to fetch. Does anybody know what I'm doing wrong ?
Please add "Content Type" and "Accept" properties in your header, I think it could be a reason of your error. Let me know if it works :-)
fetch('"http://127.0.0.1:8000/api/v1/articlesapi/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization':'Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e'
},
body: JSON.stringify({data: "your data"})
}).then(res=>res.json())
.then(res => console.log(res));
The instagram "server side workflow" for authenticating a user and giving them a session access token doesn't work. First part works in that I can get a code back from here:
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
However, when posting this code to
https://api.instagram.com/oauth/access_token
in order to obtain the access token, it just response with "YOU MUST PROVIDE A CLIENT ID", even though I have provided this as part of the form data - the same client id I used to get the code in the first place!
Here is the code I am using:
getIgToken: function (igCode) {
let data = {
client_id: config.imported.instagram.client_id,
client_secret: config.imported.instagram.client_secret,
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:5000/app/scrape',
code: igCode
}
return $http({
method: 'POST',
url: 'https://api.instagram.com/oauth/access_token',
data: data,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
}
Apparently others have reported problems with posting the data as json, which have then been resolved by using "application/x-www-form-urlencoded" - however this doesn't seem to work either now.
Here is the exact error message returned:
{error_type: "OAuthException", code: 400, error_message: "You must provide a
client_id"}
code:400
error_message:"You must provide a client_id"
error_type:"OAuthException"
grant_type should be 'authorization_code'
convert the data object to json format , try
data: JSON.stringify(data),
your code will look like this
getIgToken: function (igCode) {
let data = {
client_id: config.imported.instagram.client_id,
client_secret: config.imported.instagram.client_secret,
grant_type: 'authorisation_code',
redirect_uri: 'http://localhost:5000/app/scrape',
code: igCode
}
var jsonData= JSON.stringify(data)
return $http({
method: 'POST',
url: 'https://api.instagram.com/oauth/access_token',
data: jsonData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
}
I wrote the below code to send the $http.post request
$http({
url: '/OA_HTML/ReportColumnSelection.jsp',
method: 'POST',
data: JSON.stringify({myData : $scope.reportColumns}),
headers: {'Content-Type': 'application/json;charset=utf-8'}
})
.success(function(response){
$scope.viewColumns = response.columnData;
})
.error(function(response){
//Error Log
console.log('Inside saveReportColumns Error');
});
Now the problem is i'm unable to get the "myData" JSON in ReportColumnSelection.jsp
request.getParameter("myData");
Please let me know if i'm doing anything wrong.
AngularJS Version 1.4.7
Code to save report columns:
$scope.saveReportColumns = function () {
console.log('Inside saveReportColumns');
$http({ url: '/OA_HTML/eis/jsp/reporting/reports/newreport/columnselection/EISRSCReportColumn‌​SelectionAM.jsp',
method: 'POST',
data: JSON.stringify({myData:$scope.reportColumns}),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).success(function(response){}).error(function(response){
//Error Log console.log('Inside saveReportColumns Error');
});
};
The $http services default content type is application/json, which your JSP cannot parse.
You can either,
change the content type of the request to application/x-www-form-urlencoded;charset=utf-8 (which might have other implications)
or
read it as a stream like below.
InputStream body = request.getInputStream();
It might be a good idea to leave the content type as it is, and instead read the request body and parse it with a library such as google/json
BufferedReader reader = request.getReader();
Gson gson = new Gson();
I am trying to pass JSON string in ajax request. This is my code.
NewOrder = JSON.stringify (NewOrder);
alert (NewOrder);
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: "mydata="+ NewOrder
};
$http(req)
.success(function (data, status, headers, config) {
alert ('success');
})
.error(function (data, status, headers, config) {
alert (status);
alert (data);
alert ('Error')
});
alert (NewOrder) gives -
{"ItemList":[{"ItemName":"Quality Plus Pure Besan 500 GM","Quantity":1,"MRP":"28.00","SellPrice":"25.00"}],"CustomerID":1,"DeliverySlot":2,"PaymentMode":1}
Which seems to be a valid JSON string.
But in script side I am getting following error. in this line
my $decdata = decode_json($cgi->param('mydata'));
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)")
Can please someone help me why i am getting this error?
$cgi->param('myData') returns the query param string 'mydata', which in your case is not sent.
You're posting the json data in the request body of your http post payload, and not as a query/form param. In that case, you'd need some other function to read the contents of the request body in your server-side script.
which happens to be:
my $data = $query->param('POSTDATA');
as described in here: http://search.cpan.org/~lds/CGI.pm-3.43/CGI.pm#HANDLING_NON-URLENCODED_ARGUMENTS
Also you should remove the "mydata=" from your json in the body you post, because http request payload bodies do not have parameter names (they're for query/form-params only).
Your end code should be like this:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: NewOrder
};
and the servers side:
my $decdata = decode_json($query->param('POSTDATA'));
I think it may be related to this issue: AngularJs $http.post() does not send data
Usually I would post data like this:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: {"mydata" : NewOrder}
};
However I am assuming that you are expecting the data as request params from this:
my $decdata = decode_json($cgi->param('mydata'));
If that is the case then the linked SO question is what you are looking for.
Angular $http.post accepts two params as url and payload
var url = '/cgi-bin/PlaceOrder.pl';
var payLoad = {'myData' :JSON.stringify(NewOrder)};
$http.post(url, payLoad)
.success(function(data) {
console.log(success);
})
At the server side, while fetching the required json string from the request param and then desearlize the json as following:
$result = $cgi->param('myData');
my $decdata = decode_json($result);