FrisbyJS returning 415 instead of 200 - frisby.js

I just started using FrisbyJS to test a rest service we are building out. I'm getting an error and that it says it's expecting a 415 instead of 200. My code looks like:
var frisby = require("frisby");
var apiUrl = // api url
frisby.create("GET resource by id " + "43")
.get(apiUrl + "/book/43")
.expectStatus(200)
.toss();
The exact error message is:
Expected 415 to equal 200.
When I put the exact url that jasmine spits out to me when I run my test into a browser, or try it as a GET request in Postman on Chrome, it works and I get a 200 back. For some reason I get a 415 though for my call. Is there something I am missing?
Edit
Tried to debug some more and if I just do
frisby.create("GET resource by id " + "43")
.get(apiUrl + "/book/43")
.inspectJSON()
.toss();
I get this error:
Error parsing JSON string: Unexpected end of input
Which makes me thing that our rest service is doing something funny. However when I view this url in a browser or Postman like I said, it works fine.

Try this in your solution:
frisby.globalSetup({
request: {
headers: {
'Content-Type': 'application/json'
}
}
});

Related

Google scripts, using urlFetchApp() for PUT request, I cannot get a response code when server sends 204 no content response

For GET and POST requests for a private server I work with I use in Google Sheets, do something like this, and I get a proper response. I use that response to update data and just as importantly for error checking by evaluating response.getResponeCode().
function postDataToServer(params){
let myjdService = getService();
let orgId = getOrgIdForSelectedOrg();
let link = https://GoodURLForPrivateDataIWorkWithALot/neededurlParameter/anotherNeededURLParameter;
let options = {
'method': 'put',
'payload': JSON.stringify(params),
'headers': {
'Accept': 'application/vnd.PRIVATE.v3+json',
'Content-Type': 'application/vnd.PRIVATE.v3+json',
'authorization': 'Bearer ' + myPrivateService.getAccessToken()
}
};
let response = UrlFetchApp.fetch(link, options);
return response.getResponseCode();
For all the GET and POST requests I do, I get a response. And from that response I can parse a response code. But for the specific server I work with, when I edit a record using PUT, a successful edit returns this:
204 No Content
And further, the last line return response.getResponseCode() returns an error the response is undefined.
Here's the error I get for doing anything with response:
ReferenceError: response is not defined
The PUT is working. I only know this because 1) when I check if edits are made with the server, they are 2) testing the PUT in Postman at least shows me the words "204 No Content" and 3) the documentation says that's exactly what I should expect.
But I still would like to find out how to evaluate this no-content response in my Google Sheets App for proper error tracking. At least some way to get the string "204". Any ideas? I can't even get Google Sheets to do say 204.

getResponseCode() method doesn't return expected response code

I have 2 questions about Google App Script Services getResponseCode() method.
1) "Unexpected Error"
When I run the getResponseCode() method, I got "Unexpected Error...".
https://developers.google.com/apps-script/reference/url-fetch/http-response#getResponseCode()
var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
responseCode = response.getResponseCode();
Unexpected error: https://www.example.com/
※I can't tell the url for business reasons.
HTTP response status codes don't include "Unexpected Error".
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Please tell me what response codes actually return, when this error occurs?
2) getResponseCode() method didn't work as expected
When I run the code below, I got "200".
I expected "301" in response to the "http://google.com/" request.
function myFunction() {
var response = UrlFetchApp.fetch("http://google.com/");
 Logger.log(response.getResponseCode());
}
I think getResponseCode() method doesn't return actual http status codes.
Please tell me why I got "200" instead of "301".
get 301 response in browser
get 200 response instead of 301
This happens because the request is following the redirect. Take a look at the available parameters in the UrlFetchApp.fetch() method. You'll see followRedirects, which defaults to true.
Make this small change and you'll get the expected 301.
function myFunction() {
var response = UrlFetchApp.fetch("http://google.com/", { followRedirects: false });
 Logger.log(response.getResponseCode());
}

POST request not able to find url

I am new to nodejs as well as developing.
I am trying to get a set of data bat from a nutrition site in JSON format. If I formulate the url with my app and api keys along with criteria to paste into the browser I get a JSON data ok. When I try to send a POST request as the site asks for when the request comes back it says it cannot find the url. What it is doing is attaching ':443' to the end of the host url and like I said coming back as an error:
Error: getaddrinfo ENOTFOUND https://api.nutritionix.com/v1_1/search https://api.nutritionix.com/v1_1/search:443
What I would like to do is after the end of the url is append the 'postData'.
Here is my code:
var https = require('https');
var querystring = require('querystring');
var postData = { // Nutrionix required JSON formt
"appId":"MY_APP_KEY",
"appKey":"MY_API_KEY",
"query": "Lentils",
"fields": ["item_name", "nf_calories", "nf_serving_size_qty", "nf_serving_size_unit"],
"sort":{
"field":"score",
"order":"desc"
},
"filters":{
"item_type":"2"
}
};
console.log("This is header dta" + postData);
postBody = querystring.stringify(postData);
var post_options = {
host:"https://api.nutritionix.com/v1_1/search",
"port":"443",
method:"post",
"path":"/",
headers:{"Content-Type":"application/json",
'Content-Length': postBody.length
}
}
console.log(post_options);
var request = https.request(post_options,function(response){
return response;
});
I also am passing this data into the dev HTTP add-on in Chrome and getting back the proper response.
Any help would be appreciated.
Can you please take a look at this documentation?
It seems that you don't need to mention HTTPS
Take the port off, 443 is the default for HTTPS.

ajax request parsing: SyntaxError: Unexpected token :

I make an ajax request:
$.ajax({
url: "http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en&jsoncallback=?",
dataType: 'json'
});
and get an error:
SyntaxError: Unexpected token :
When I click on that error in dev tools I see such an object which looks pretty ok for me:
{
"quoteText":"Reality leaves a lot to the imagination. ",
"quoteAuthor":"John Lennon",
"senderName":"",
"senderLink":"",
"quoteLink":"http://forismatic.com/en/9dceb1ebf1/"
}
Where is the problem? I'm unable to find the solution.
Putting a =? in a URL overrides the dataType and tells jQuery to make a JSONP request instead of an XHR request.
The URL you are requesting returns JSON, not JSONP, so you get an error.
Remove &jsoncallback=? from the URL.
You will then get this error:
XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en&js. No 'Access-Control-Allow-Origin' header is present on the requested resource.
… which is explained in this question.

jQuery not handling JSON response from AJAX POST

Updated: I'm posting HTML FORM data but expecting to receive JSON data. I am not trying to POST JSON data.
I am trying to get a JSON response back from doing a HTML FORM POST request. I have successfully received a JSON back when using a simple HTML FORM POST request (i.e. not AJAX). My JSON response from the HTML FORM POST is this:
{"success":true,"data":1234567}
The problem occurs when I try to handle the request and response with jQuery's .ajax().
$.ajax({
type: "POST",
url: URL,
data: data1,
dataType: "json",
success: function(data, textStatus, jqXHR) {
alert ("success");
},
error: function(xhr, status, error) {
alert ("Error: " + error);
}
});
After running the above code and debugging in Firebug, it appears that the POST request is going through, but something is going wrong on the handling of the response. Firebug tells me the following regarding the HTTP response from the POST request:
Response Headers
Cache-Control private
Content-Length 31
Content-Type application/json; charset=utf-8
...
So it appears that the 31 bytes of data is being sent. However, when debugging the actual Javascript, the error function gets called and the xhr object is this:
Object { readyState=0, status=0, statusText="error"}
I know the jQuery.ajax() document states that "In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown." However, I believe my JSON is valid as I have checked it at jsonlint.com.
What else could be going wrong?
It looks to me like you are getting a server error. I would check the status code of the response and fix whatever is causing the request to fail on the server.
your getting an error because data1 is not formatted in json, so when it receives the data it gets a parse error. data1 needs to be formatted:
data1={"apikey":apikey,
"firstname":fName
}
I was having the same problem. It seems that this is an issue with Cross Domain.
Finding this SO answer: https://stackoverflow.com/a/7605563/154513
helped me.
Some times Jquery return Internal Error 500 for currectly data.
There is example for read the same json data withour error
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://reqres.in/api/products/3", true);
xhr.onload = function(){
console.log(xhr.responseText);
};
xhr.send();