I'm writing a test using SlimerJS for a website and need to check the response body coming from the server. I'm using the following piece of code to get the response:
page.onResourceReceived = function (response) {
console.log(JSON.stringify(response));
};
I do receive the response but since by default to prevent too much memory usage SlimerJS keeps the response body empty I too receive an empty body, unless I tell it not to keep the body empty for certain formats using something like this:
webpage.captureContent = [ /css/, /image\/.*/ ]
I understand this works well for files with extensions like css,jpg and avi, but what about an AJAX response coming from the server. The response is in JSON format and the response body is left empty.
By looking at the response header you can tell that the response type is in text/html so by using the following code you can get the body.
page.captureContent = [/text/, /html/]
Related
I want to parsing this response from http get and display the value into a detail modal but I dont know how to parse it. I have using arc to show me the response of my http get,here is my image of my response using arc.
here is my.js file
$http.get('.....a='+$scope.month).then(function(response){
$scope.coba = response.data;
Use JSON.stringify(response.data) or angular.toJson(response.data), it will parse the http response into JSON.
If it is failing, means your response is not exact JSON
I'm trying to use instagrams api, without having to authenticate.
if I go to: https://www.instagram.com/explore/tags/chicago/?__a=1
I get a json response.
I'm trying to build an angular 4 provider that returns that data.
getInsta(term){
return this.jsonp.request(this.url+term+'/?__a=1&callback=__ng_jsonp__.__req0.finished')
.map(res => {
console.log(res.json());
});
}
I've tried "callback" and "c". I've tried JSONP_CALLBACK.
I get the error of:
"SyntaxError: Unexpected token ':'. Parse error. - In chicago:1"
and
"JSONP injected script did not invoke callback"
If I click on the unexpected token error, it brings me to the response with all the json data in it. So that means it's coming through, I just cant access it!
Any idea how i can get around this?
Here is a screenshot of the error and when clicking on the error
JSONP is a method to fetch data cross origin, it works because it injects a script tag to the body when the src of the file contains the callback function name.
<script src="http://ani.site.com/api/?callback=myGlobalFunc">
And it assumes that there is a global func on the window with the name myGlobalFunc.
The response of that call gonna look like: myGlobalFunc({data: 'data1'}).
Invocation of the function with one argument which is the data.
In your case, Instagram API return JSON not JSONP.
There for you can't use that mechanism.
I'm creating a firebase application which uses firebase-cloud-functions.
index.js
exports.auth = functions.https.onRequest((request, response) => {
response.status(200).send({
status : "Some Status"
});
}
This is very simple functions. I want to make a POST request on the endpoint with some payload. When I tested the API using Firebase Cloud Function Emulator and POSTman with bad json
{
"phoneNumber: "9632725300"
}
The server just crashed! My question is how to handle the bad request in firebase functions like these.
with this error
The server did not crash. You have sent it a bad request (malformed JSON) and it responded perfectly with a status code 400 which is "Bad Request".
You'd rather correct your JSON...
EDIT:
If you really wanted to be able to send invalid JSON, you could do so by circumventing the JSON body parser. To do so, you could either change your request to have a content-type header set to "text/plain". This content-type will use the text body parser, which will not parse any JSON.
Note that doing so will require you to handle the JSON parsing yourself, but will permit to handle to error yourself using a try-catch.
let json;
try {
json = JSON.parse(json);
} catch (e) {
// Handle JSON error.
}
Taken from https://firebase.google.com/docs/functions/http-events
What you're experiencing is not actually a server crash. In fact, technically, by using Cloud Functions, you don't have a server to crash. (For this reason they're called "Serverless Infrastructure") Each request / operation you perform on Cloud Functions is kind of like a brand new server. Which is actually what's fantastic about Cloud Functions in general. (This is an overly simplified explanation, I'd suggest reading up a bit more about it for a better in depth explanation)
That being said, from what I understand you're trying to figure out if the JSON you got is invalid (bad) or not. Occasionally, when I have to hook up a bunch of external services, rarely, but sometimes, they return a bad JSON that my Cloud Functions can't parse, therefore throws an error.
The solution is to put your JSON.parse in to a separate function and a try / catch block like this:
function safelyParseJSON (json) {
var parsed;
try {
parsed = JSON.parse(json);
} catch (e) {
// BAD JSON, DO SOMETHING ABOUT THIS HERE.
}
return parsed; // will be undefined if it's a bad json!
}
function doSomethingAwesome () {
var parsedJSON = safelyParseJSON(data);
// Now if parsedJSON is undefined you know it was a bad one,
// And if it's defined you know it's a good one.
}
With this helper function, if you have to deal with a lot of external JSON resources, you can easily determine if the JSON you're trying to parse is good, and if not, you can at least handle the error your way.
Hope this helps :)
{\n\t"phoneNumber: "9632725300"\n}
From the screenshot, I see that the JSON is invalid or malformed. It contains newline (\n) and tab space (\t) characters. Also, the key "phoneNumber" is not wrapped in double quotes, which again invalidates the JSON.
Here's a valid format of the JSON that the server should receive
{
"phoneNumber": "9632725300"
}
I'm just following tutorials and figuring out how to handle get requests in NodeJS.
Here are snippets of my code:
NodeJS:
router.get('/test', function(request, response, next) {
console.log("Received Get Request");
response.jsonp({
data: 'test'
});
});
Angular:
$http.get("http://localhost:3000/test").
success(function(response) {
alert("OK");
}).
error(function(response) {
alert("FAIL");
});
If I try to access the link directly # localhost:3000/test, I'm able to receive the JSON message correctly. But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response)
SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of
the JSON data
The reason for that is because the response is empty but the response code is 200 in both cases.
I've tried searching for hours but maybe someone can enlighten me on this?
you could try and send
res.send('test')
and then on your http request you can use 'then'
$http.get("http://localhost:3000/test").then(function(res) {
console.log(res);
})
unlike success, then will give you a complete object (with 'test' - string as res.data)
success will bring you only the data;
then will bring you the whole object (with the status and such)..
now about that jsonp .. it's used to override a json response. you could simply use 'res.json({data: 'test'})' and it should also work for you..
hope it helps
You're using jsonp in node, which you probably don't need to. This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed)
Try changing the server to look like
response.json({
data: 'test'
});
If you look in the Network pane of the developer tools, you should be able to see the raw response. It should look something like:
{"data" : "test"}
I'm trying to switch from using the normal mootools request to request.JSON since I'm using exclusively json to communicate between the client and my server. I have a json request defined as:
var jsonRequest = new Request.JSON({
url: '/ServletContext/servlet',
onRequest: function(){
// Just a class to make the cursor change to progress
container.addClass('request-waiting');
},
// validationMessages should be a json object containing
// messages on problems validating user input from server
onSuccess: function(validationMessages){
container.removeClass('request-waiting');
},
onFailure: function(requestObj){
container.removeClass('request-waiting');
}
}).post({'context': context,'title': title});
I'm currently testing this in chrome, and the request is posting fine, and returning an http 200 with the contents I'm expecting; but the onFailure call back keeps getting called. I'm wondering why the onSuccess method is not being called.
The json string I'm sending back (intentionally) in the response is:
"{titleErrors: [], contextErrors: ['Context must be more than 40 characters']}"
I'm using mootools 1.3, and tomcat 7.
EDIT: After going up the mootools stack a bit, I found a call to json.decode and this is failing. I'm guessing that is because my json string is malformed. I haven't been using json that long, so that wouldn't surprise me but I would have thought that this would work. I'm looking into this but if you're able to eyeball my json and see the problem then that would be appreciated.
The json was malformed. I had this:
{titleErrors: [], contextErrors: ["Context must be more than 40 characters"]}
and it should have been this (note quotes around variable names):
{"titleErrors": [], "contextErrors": ["Context must be more than 40 characters"]}