Post request to golang server using polymer core-ajax? - ajax

I am trying to make a POST request using polymer core-ajax to server runnung golang. After a lot of search (because i am new to this stuff) i ended up with the following code. Also, GET request is working perfect. POST parameters i dont understand how to pass using core-ajax.
<polymer-element name="register-user" attributes="url">
<template>
<core-ajax id="ajaxSubmit" url="{{url}}" contentType="application/json" handleAs="json" method="post" on-core-response="{{response}}"></core-ajax>
<style type="text/css">
</style>
</template>
<script>
Polymer({
buttonListener: function() {
var data = '{"Name":"'+ this.name +'", "Email":"'+ this.email +'"}';
this.$.ajaxSubmit.data = data;
this.$.ajaxSubmit.go();
console.log(data);
},
response: function(oldValue){
console.log(this.response);
}
});
</script>
</polymer-element>
above code returns 500 (Internal Server Error) however when i make a POST request using curl i.e
curl -i -H 'Content-Type: application/json' -d '{"Name":"Batman",
"Email":"batman#gmail.com"}' http://so.me.ip.ad:8080/register
it works as it should and returns
HTTP/1.1 200 OK
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Wed, 29 Apr 2015 05:40:15 GMT
Content-Length: 117
{
"id": 3,
"name": "Batman",
"email": "batman#gmail.com",
"createdAt": "2015-04-29T05:40:15.073491143Z"
}
also, i have a CORS middleware set up on server i.e
api.Use(&rest.CorsMiddleware{
RejectNonCorsRequests: false,
OriginValidator: func(origin string, request *rest.Request) bool {
return origin == "http://0.0.0.0:8000"
},
AllowedMethods: []string{"GET", "POST", "PUT"},
AllowedHeaders: []string{
"Accept", "Content-Type", "X-Custom-Header", "Origin"},
AccessControlAllowCredentials: true,
AccessControlMaxAge: 3600,
})
What am i doing wrong? Any feedback will be of great help! Thanks ^.^
Edit : here is a little more info if it can help..

I think CORS is a red herring. The problem may be that you are sending the data form-encoded and not as json. I found a bug from a user with a similar problem.
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Fri, 12 Dec 2014 04:29:59 GMT
Content-Length: 71
{
"Error": "invalid character '\\'' looking for beginning of value"
}
Perhaps you should use .body instead of .data? See this answer.
From the polymer documentation:
body: Optional raw body content to send when method === "POST".
Example:
<core-ajax method="POST" auto url="http://somesite.com"
body='{"foo":1, "bar":2}'>
</core-ajax>

Related

Getting 400 Bad Request with Grails Spring Security Rest Plugin

I'm trying grails restful spring security rest plugin.
I'm using Grails 2.5.2 with spring-security-rest:1.5.2.
I'm unable to make login work with the following ajax call. I get 400 bad request. But if I try to use CURL command it works! I don't understand what's wrong.
That's the ajax post call:
var config = {
type : 'POST'
,url : '/api/login'
,data : {username:"xxxx",password:"xxxx"}
,async : false
,dataType : 'JSON'
,contentType: "application/json;charset=utf-8"
,success: function(response) {
console.dir(response);
}
,error : function (response) {
console.dir(response);
}
}
$.ajax(config);
Spring rest plugin configuration inside Config.groovy is:
grails.plugin.springsecurity.filterChain.chainMap = [
'/api/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter', // Stateless chain
'/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter' // Traditional chain
]
grails.plugin.springsecurity.rest.login.active=true
grails.plugin.springsecurity.rest.login.failureStatusCode=401
grails.plugin.springsecurity.rest.token.validation.active=true
This is my curl command:
curl -i -X POST -H "Content-Type: application/json" -d '{"username":"xxxxx", "password":"xxxx"}' http://localhost:8080/api/login
and that's the response:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Content-Length: 2172
Date: Tue, 01 Mar 2016 13:28:42 GMT
{"username":"xxxxxx","roles":["ROLE_ADMIN"],"token_type":"Bearer","access_token":"eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NTY4NDI1MjIsInN1YiI6ImFkbWluZGllIiwicHJpbmNpcGFsIjoiSDRzSUFBQUFBQUFBQUpWU3YwOFVRUlIrZXg2QlNLSmdnb2tGTm1KbjloTG92RWJBMDJDV3czQmNnNGxrYnZleERqYzdzODdNSG5jTnVVb0xDZ2hJWXVLXC93SDhpalgrQWdZS1cydFkzeThFZU5JU3BkdDk4Kzczdnh4NWZ3SWpSTUJkcnhvWHhVNUhGWFBvbTFWekdCc05NYzl2ek00TTZRcHNqM3VmQUprM2c4bmdsOEFJbzhjakNrMkNMZFZoRk1CbFhWbHBiR05wcVY4T3MwdkdBY1ZPekJMZVZidnZYM0tIU2VHTkJRZTI5S2NIb09reXlNRlNadEhVb................... etc.etc.
Any help is really appreciated!
Basing on official docs you should change dataType to 'json':
dataType (default: Intelligent Guess (xml, json, script, or html))
btw did you try to remove async : false from config and check it?

Parse.com Analytics not showing

I'm trying to connect to Parse.com 's REST-API via NSURLConnection to track AppOpened metadata.
I get 200 OK back from the API and the headers are the same to the cURL headers but my API calls are not being represented in the data browser on Parse.com . Is NSURLConnection doing something silly I don't know of? API response is the same but one request gets represented while the other one isn't.
NSLog output:
<NSHTTPURLResponse: 0x7ff5eb331ca0> { URL: https://api.parse.com/1/events/AppOpened } { status code: 200, headers {
"Access-Control-Allow-Methods" = "*";
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 3;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 04 Jan 2015 22:42:54 GMT";
Server = "nginx/1.6.0";
"X-Parse-Platform" = G1;
"X-Runtime" = "0.019842";
} }
cURL output:
HTTP/1.1 200 OK
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Sun, 04 Jan 2015 23:03:51 GMT
Server: nginx/1.6.0
X-Parse-Platform: G1
X-Runtime: 0.012325
Content-Length: 3
Connection: keep-alive
{}
It's the same output. What am I doing wrong? Has anyone experience with this?
Turns out Parse was showing funny API keys the moment I copied them out of the cURL example they provide in their lovely docs. Don't know whose analytics I screwed over but I'm terribly sorry and it wasn't my fault!
Always copy your API keys out of [Your-Parse-App-Name]->Settings->Keys
It probably was just a stupid glitch that happened on the Server.

Parse response 124, timed out for simple GET request

For the life of me I can't figure this out. I have the following code up on Parse.com:
Parse.Cloud.httpRequest({
method: "GET",
url: 'http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?9ZIG%EF%BC%B0%EF%BC%B2%EF%BC',
success: function(httpResponse) {
response.success(httpResponse.text);
},
error: function(httpResponse) {
response.error('Request failed with response ' + httpResponse.status);
}
});
It's a simple GET request, but it hangs and after about 10 seconds, Parse.com will time out with error 124: Request Timed Out.
If I substitute https://www.google.com or https://parse.com, it will deliver me the results instantaneously. So, I thought it might be the page I'm trying to load, but I can access http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?9ZIG%EF%BC%B0%EF%BC%B2%EF%BC on my browser and it loads pretty much instantaneously.
The request also loads pretty much instantaneously when I use cURL:
curl -v http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?9ZIG%EF%BC%B0%EF%BC%B2%EF%BC
* Adding handle: conn: 0x7fcb0c800000
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fcb0c800000) send_pipe: 1, recv_pipe: 0
* About to connect() to www.csse.monash.edu.au port 80 (#0)
* Trying 130.194.64.145...
* Connected to www.csse.monash.edu.au (130.194.64.145) port 80 (#0)
> GET /~jwb/cgi-bin/wwwjdic.cgi?9ZIG%EF%BC%B0%EF%BC%B2%EF%BC HTTP/1.1
> User-Agent: curl/7.30.0
> Host: www.csse.monash.edu.au
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sun, 21 Sep 2014 02:30:23 GMT
* Server Apache/1.3.26 (Unix) mod_layout/3.0.4 mod_ssl/2.8.10 OpenSSL/0.9.6e is not blacklisted
< Server: Apache/1.3.26 (Unix) mod_layout/3.0.4 mod_ssl/2.8.10 OpenSSL/0.9.6e
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD><META http-equiv="Content-Type" content="text/html; charset=UTF-8"><TITLE>WWWJDIC: Text/word translation display</TITLE>
</HEAD><BODY>
<br>
<FONT color="red">PR</FONT>。<br>
<ul><li> PR 【ピーアール】 (n) (See パブリックリレーションズ) public relations; PR; ED </li>
</ul><br>
</BODY>
</HTML>
* Connection #0 to host www.csse.monash.edu.au left intact
I feel like I must be missing something really simple. I added all the headers and none seemed to make a difference. Does anyone have an idea?
OK I've worked this out and it's taken me HOURS. Firstly Parse will not accept httpRequests outside of Cloud Code beforeSave, afterSave and cloud functions. You will also have to use a Parse Promise.
So in main.js in your Cloud Code setup create the function testParse like this:
Parse.Cloud.define("testParse", function(request, response) {
var promises = [];
promises.push(Parse.Cloud.httpRequest({
method: "GET",
url: 'http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?9ZIG%EF%BC%B0%EF%BC%B2%EF%BC'
});
Parse.Promise.when(promises).then(function(results) {
response.success(results.status);
}, function(error) {
response.error(error);
});
});
To call the function you will use
Parse.Cloud.run('testParse');
This solution works. Frustrating though, only 10% of the time. I still get timeouts.
Edit:
OK got it to work. On the Parse.Cloud.define error response call the function again:
Parse.Promise.when(promises).then(function(results) {
response.success(results.status);
}, function(error) {
Parse.Cloud.run('testParse');
});

Http multipart request using Google Drive API

I am trying to send HTTP multipart request using Google Drive API to insert file in Google Drive.
I am following the link below : Multipart upload
However, I am getting a Bad request error.
Below is the request string which I have created using the documentation link above:
String content = '\r\n--' + boundary + '\r\n';
content +='Content-Type: '+'application/json; charset=UTF-8'+'\r\n\r\n';
content +='{' + '\r\n';
content +='"title": "My File"'+'\r\n';
content +='}'+'\r\n\r\n';
content += '--'+boundary + '\r\n';
content +='Content-Type: '+'text/plain'+'\r\n';
content += EncodingUtil.base64Encode(b)+'\r\n';
content += '-'+boundary+'-\r\n';
Please can someone tell me what I am missing here ??
I was having trouble with this as well,
but if you look at the code for the google drive API on github:
Github Drive API
The request parameters accept a media object, which can have a body and mimeType.
I was working with a service account, and this lets you upload files directly to drive.
auth.getApplicationDefault(function(err, authClient) {
if (err) {
console.log('Authentication failed because of ', err);
return;
}
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
var scopes = ['https://www.googleapis.com/auth/drive'];
authClient = authClient.createScoped(scopes);
}
var request = {
project: "YOUR_PROJECT",
auth: authClient,
resource: {
parents: ['blah']
},
media: {
body: 'hi',
mimeType: 'text/plain'
}
};
drive.files.create(request, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
});
I had this problem too and after trying some changes I finally reached a working example:
Header :
POST /upload/drive/v2/files?uploadType=multipart&access_token=ya29.CjAmA2j6eonCiROaNum-V1cWdFVH2vXpNiXAsXK6iLPu7K54tD4uNsmH-eEycMcnaBE HTTP/1.1
Host: www.googleapis.com
Accept: */*
Content-Type: multipart/related; boundary="foo_bar_baz"
Content-Length: 150
remember to add boundary="foo_bar_baz" in Content-Type field
Body :
--foo_bar_baz
Content-Type: application/json; charset=UTF-8
{
"title": "My File"
}
--foo_bar_baz
Content-Type: text/txt
JPEG data
--foo_bar_baz--

web api returning invalid json - Unexpected token

I have a web api2 controller returning a collection of complex types.
This setup has been working for some time, until it started choking on a record today.
It appears that one of the objects (out of 122), is now breaking JSON.parse on the client.
Fiddler is also not able to parse JSON. As soon as i skip the "bad" object, valid JSON is returned.
here are the headers from the breaking response:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcZGV2XEJTR1xBcHBzXENhbXBGb3JjZVx0cnVua1xQZXJtYWwuQlNHLkNhbXBGb3JjZS5XZWJcYXBpXGNhbXBcdGVtcGxhdGVz?=
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Tue, 18 Mar 2014 00:50:14 GMT
Content-Length: 1312
if i look at the serialized object string on the client, and paste it into jsonLint it points to this area:
"HtmlValue": "<html>\n\n<body...
this looks pretty much the same as all the "good" objects.. so i'm a bit stumped.
since web api is encoding the response as JSON, why would it allow breaking characters?
update
here is the breaking json (i retrieved it on client prior to deserialization:
[
{
"$id": "1",
"Id": "00Xg0000000MBGoEAO",
"Name": "Template Test",
"Body": null,
"HtmlValue": "<html>\n\n<body lang=EN-US style='tab-interval:.5in'>\n\n<div class=Section1>\n\n<p class=MsoNormal><span class=SpellE><span style='font-size:20.0pt;line-height:\n115%;font-family:\"Franklin Gothic Book\",\"sans-serif\"'></span></span><span\nstyle='font-size:20.0pt;line-height:115%;font-family:\"Franklin Gothic Book\",\"sans-serif\"'><o:p></o:p></span></p>\n\n<p class=MsoNormal>testing </p>\n\n<p class=MsoNormal><o:p> </o:p></p>\n\n</div>\n\n
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Chrome"}
</script>
<script type="text/javascript" src="http: //localhost: 61319/6cd9cb905b1e4b5bb51cb5a36ea0bd17/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>\n\n</html>",
"Subject": "Test",
"IsActive": true
}
]
the plot thickens.
this part is being inject into the HTML property
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Chrome"}
</script>
<script type="text/javascript" src="http: //localhost: 61319/6cd9cb905b1e4b5bb51cb5a36ea0bd17/browserLink" async="async"></script>
<!-- End Browser Link -->
when i step through the code on the server, this snipped is not there, but when i view it in fiddler, i can see it injected in the response!

Resources