Invalid JSON GET Request Express.js - ajax

While writing an API, I have come across a very thorny error: when I try to do a res.send(INSERT JSON) with a Content-Type header application/json (a default for most AJAX), I get an invalid json error. When I set the content-type to anything else (eg. text/plain), I get the correct response, but in order to use some front-end frameworks, I need to support application/json. Here is the actual error message:
Error: invalid json
at Object.exports.error (/Users/Brad/node_modules/express/node_modules/connect/lib/utils.js:44:13)
at IncomingMessage.module.exports (/Users/Brad/node_modules/express/node_modules/connect/lib/middleware/json.js:68:73)
at IncomingMessage.EventEmitter.emit (events.js:85:17)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socket.ondata (http.js:1680:22)
at TCP.onread (net.js:410:27)
My server code is below:
app.configure(function () {
app.use(express.bodyParser());
app.use(express.cookieParser('SALT'));
app.use(express.static(__dirname + '/static/'));
app.use(express.session());
});
app.get('/users', function(req, res) {
res.send({'test': 'test'});
});
Here is an picture of my Postman setup--I am using the Postman Chrome extension to test my API:

I believe the problem is that you want to be using Content-Type header in your servers response; not in your request Content-Type header.
When you use the Content-Type header in your request, Express will read the Content-Type and attempt to interpret the provided information as that Content-Type, in this case, as JSON. Because this is a GET request and thus has no body, Express is trying to interpret an empty string as JSON, which is giving you the error.

Related

Postgraphile StatusCode: 405, ReasonPhrase: 'Method Not Allowed

I use Postgraphile locally and it work very well.
I want to send a HttpClient post requset in my Application, but it does not work and I get this error:
StatusCode: 405, ReasonPhrase: 'Method Not Allowed
hier is my code:
using (HttpClient httpClient = new HttpClient())
{
string content = "query {accounts {nodes {id,name,street,postalcode,city}}}";
var httpConent = new StringContent(content, Encoding.UTF8, "application/json");
var responseMessage = await httpClient.PostAsync("http://localhost:5000/graphiql", httpConent);
var result = responseMessage.Content.ReadAsStringAsync();
}
In line 5 of your code snippet, you're submitting to the /graphiql URL (which is for the GraphiQL GUI), you should be submitting to /graphql.
In line 4 of your snippet, you are claiming the content variable is application/json, but it is in fact a GraphQL string. You should be submitting something like {"query":"{__typename}"} as application/json.
You do not appear to be issuing an Accept: application/json header.
I suggest you use the network debugging tools of your web browser to inspect exactly what the browser is doing when it runs the GraphQL query, and compare that with what you are attempting to do with your code. You might also refer to the GraphQL-over-HTTP specification: https://graphql.github.io/graphql-over-http/draft/

Amazon CORS-enabled api returns no 'Access-Control_allow_Origin' header

After setting up Amazon API Gateway CORS as instructed, I still get the following error when send an Ajax POST request.
XMLHttpRequest cannot load https://-------.execute-api.us-west-2.amazonaws.com/--------. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://------.s3-website-us-west-2.amazonaws.com' is therefore not allowed access. The response had HTTP status code 400.
I'm using Amazon S3 to host the website, which does not support web script so I can't use python or php to fix this.
I'd really appreciate any help.
Could it be that you're using Lambda-proxy integration and your Lambda is not returning those headers? If that's the case, you have to add those headers yourself.
This is how I use to create the response that I return using callback(null, response).
function createResponse(statusCode, body) {
const headers = {
'Access-Control-Allow-Origin': '*',
}
return {
headers,
statusCode,
body: body ? JSON.stringify(body) : undefined,
}
}

Why does JSONP work with JSON-formatted data?

There is a URL I am using in a project of mine, that is working just fine. I make a request from one web server, to a different IP address, invoking a page that outputs data in this format:
[{"PhoneNumber":"+123456789","Name":"Mark"},
{"PhoneNumber":"+123456789","Name":"Josh"},
{"PhoneNumber":"+123456789","Name":"Alex"},
{"PhoneNumber":"+123456789","Name":"John"},
{"PhoneNumber":"+123456789","Name":"Sean"}]
And I can get and process that data with a function call such as this:
$.ajax({
url: serverAddress + "/getpeople",
dataType: "jsonp",
timeout: 4000,
success: function(response) {
for(var i in response) {
alert(response[i].Name);
}
}
});
Here is what's confusing me. From what I've learned about JSONP so far, it isn't actually data, but is instead a function. So the response should be wrapped in a function call, such as callback(), and then I could implement a function callback(data) {} in my project to process the data.
But in this case, the data seems to be just JSON data, which I think should cause a cross-origin error to be generated? But it doesn't.
When I try to call another URL from the same server, fetching an ordinary plain text file, then I do get a cross-origin error, which complains in the console:
Reason: CORS header 'Access-Control-Allow-Origin' missing
But the original getpeople URL does not have that header either. When I examine the response headers in Firefox's document inspector, all of the headers are:
Connection: "close"
Content-Type: "text/html;charset=utf-8"
Date: "Mon, 5 Oct 2015 08:29:07 GMT"
Server: "ServerName/1.1.10011.2211"
So:
The data is not formatted as a JSONP callback
It is served from a different IP address than the web application
The response doesn't have a Access-Control-Allow-Origin header
Why does this work?

How to get value from header authorization bearer?

My server give response header authorization bearer.
How can I get this value in angular?
When you use $http, the third parameter of the promise callback contains the response headers. You should be able to get your header from there.
With the $http service you can receive the headers through the success functions response object. You can access this property through
$http(....).success(function(result, status, headers, config){
var myAuthHeader = headers("myAuthorizationHeader");
... Do something with your headers....
}
})

Get cookie from AJAX repsonse

I'm writing a chrome extension that uses AJAX to talk to a server. I want to read the KEY in set-cookie from AJAX response, but I cannot find a way to do this.
I have tried document.cookie and xhr.getAllResponseHeaders()
$.get(myURL,
function (output, status, xhr) {
console.log(document.cookie); //empty
console.log(xhr.getAllResponseHeaders());
//Only Connection and Content-Type shows
}
);
The raw response header is:
Connection:Close
Content-Type:text/html
Set-Cookie:KEY=DFDSFDCB; PATH=/;
I know that according to spec, getAllResponseHeaders() is supposed to filter out set-cookie field. Is there any workaround?

Resources