why (in promise) SyntaxError: Unexpected token < in JSON at position 0? - fetch-api

I need public data, so I'm going to bring it.
total api url : https://www.chungbuk.go.kr/openapi-json/pubdata/pubMapForest.do
fetch('/openapi-json/pubdata/pubMapForest.do?pageNo=1&numOfRows=2').then(
(data) => data.json()).then(json=>console.log(json))
);
// package.json
"proxy":{
"target":"https://www.chungbuk.go.kr"
}
but I get strange data.
when i use postman, I got normal data.
What should I do?

Related

Getting 'expected { Object (message, detail) } to have property 'count' error in API testing using cypress

I want to assert the total count received from the response.
This is my code:
cy.request({
method:'GET',
url:'https://ibis-qa.droicelabs.us/api/practice/orders/?q=&limit=100',
failOnStatusCode: false,
headers:{
accept: "application/json"
}
}).then(Response => {
let body = JSON.parse(JSON.stringify(Response.body))
cy.log(body)
expect(body).has.property('count','27')
})
and this is the error that I have got
Please use
expect(body).has.property('count', 27)
as the value is a number
(see screen-shot, there are no quotes around 27)
You are not getting the JSON response you think you should have.
If go to the URL in the browser, I get this
{"message":"field required","detail":[{"loc":["header","authorization"],"msg":"field required","type":"value_error.missing"}]}
which is what is partially shown in the screenshot of the error message.
This is an error response from the server, and it means your request is not correct.
Then you can directly use the assertion like this. You don't need to parse or stringify.
expect(Response.body).to.have.property('count',27)
You can check this example from the cypress docs.

actions on google--unable to use app.tell to give response from JSON

I am trying to get my webhook to return a parsed JSON response from an API. I can log it on the console, but when I try to use app.tell; it gives me: TypeError: Cannot read property 'tell' of undefined. I am basically able to successfully get the data from the API, but I'm not able to use it in a response for some reason. Thanks for the help!
[Actions.API_TRY] () {
var request = http.get(url2, function (response) {
// data is streamed in chunks from the server
// so we have to handle the "data" event
var buffer = "",
data,
route;
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
// finished transferring data
// dump the raw data
console.log(buffer);
console.log("\n");
data = JSON.parse(buffer);
route = data.routes[0];
// extract the distance and time
console.log("Walking Distance: " + route.legs[0].distance.text);
console.log("Time: " + route.legs[0].duration.text);
this.app.tell(route.legs[0].distance.text);
});
});
}
This looks to me to be more of a JavaScript scoping issue than anything else. The error message is telling you that app is undefined. Often in Actions, you find code like yours embedded in a function which is defined inside the intent handler which is passed the instance of your Actions app (SDK or Dialog Flow).

xhrPost seems to be modifying the URL resulting in either 404 or 405?

xhrPost seems to be modifying the URL resulting in either 404 or 405.
This is from a custom widget and attempting to go to a REST service on a WebSphere Liberty server.
The rest service responds correctly when using RESTClient and building the request manually.
I am using var jsonData = JSON.stringify(domForm.toObject("TaskTemplate")); so I can verify the data is correct and sending the data as that string:
data: jsonData,
the URL is hardcoded in the form and no substitution is currently being used:
<form id="TaskTemplate" name="TaskTemplate"
data-dojo-attach-point="taskTemplateNode"
method="POST"
action="http://localhost:9080/test2/rm/tasks/64/update">
I also have a GET with a URL of "http://localhost:9080/test2/rm/tasks/64/" that is working fine.
Seems to be associated with PUT or POST...
When I do the xhrPost, I am getting the following error:
"NetworkError: 404 Not Found - http://localhost:9080/test2/undefined"
since "undefined" is seen, it is like xhrPost is doing some substitution in the hardcode URL...
I am using 1.9.2-20140219-IBM version of dojo which comes with Rational Application Developer.
I have tried both xhrPost and xhrPut with the same results.
Here is the method that is invoked when the button is pushed:
applySubmit: function() {
console.log("inside applySubmit");
var jsonData = JSON.stringify(domForm.toObject("TaskTemplate"));
console.log(jsonData);
var xhrArgs = {
// url: "http://localhost:9080/test2/rm/tasks/64/update",
data: jsonData,
preventCache: true,
timeout: 10000,
handleAs: "text",
contentType: "application/json",
load: function(data) {
console.debug("applySubmit success:" + data);
},
error: function(data) {
console.debug("applySubmit error:");
}
};
console.log("doing dojo.xhrPxxx(xhrArgs);");
var deferred = dojo.xhrPost(xhrArgs); // any need to save local var and exit?
}
In the server logs, I am seeing [WARNING ] SRVE0190E: File not found: /undefined
and that is coming from the webcontainer (makes sense given the error msg above)
So, this means it is not related to my rest service, never gets to it.
This is really starting to delay our project, so any ideas about why this might be occurring would be greatly appreciated!

Grails - render validation errors as JSON

I'm building a RESTful API and the endpoints I'm creating are using command objects to validate the request data. I'm trying to figure out the best way to render the validation errors as json. For xml responses I followed the recommendation in the Grails in Action book and did...
response.status = 403
render(contentType: "text/xml") {
errors {
eventSaleDataCommand.errors.fieldErrors.each { err ->
field(err.field)
message(g.message(error: err))
}
}
}
This works well for rendering xml responses so I'm wondering what the recommended approach for rendering json responses is?
I wanted to have some control of how the error gets displayed so for the json response I added:
def results = eventSaleDataCommand.errors.fieldErrors.toList()
def errors = []
for (error in results) {
errors.add([
'type' : 'invalid_entry',
'field' : error.field,
'rejected_value': error.rejectedValue,
'message' : error.defaultMessage
])
}
render errors as JSON
Problem with this approach is I'm using the Joda time plugin so I'm getting the following exception when I try to render the map as JSON:
Class org.codehaus.groovy.grails.web.converters.marshaller.json.GenericJavaBeanMarshaller can not access a member of class org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone with modifiers "public".
Anyone know of a way around this?
How about?
render eventSaleDataCommand.errors.fieldErrors as JSON

What changed in jQuery 1.9 to cause a $.ajax call to fail with syntax error

I'm making a REST DELETE call, which returns a 204. In jQuery 1.8.3 this works, and hits the request.done callback. But if I use 1.9 it goes to request.fail with a parsererror in the textStatus and a 'SyntaxError: Unexpected end of input' in the errorThrown.
remove = function (complete) {
var self = this;
var request = $.ajax({
context: self,
url: "/v1/item/" + itemId,
dataType: "json",
type: "DELETE"
});
request.done(removeCallback);
request.fail(function (xhr, textStatus, errorThrown) {
alert(errorThrown);
});
},
Anyone know what has changed in 1.9 that would cause this to fail, and what needs to change in order to fix it?
So, answering my own question it looks like this is in fact the problem:
From the jQuery upgrade guide
jQuery.ajax returning a JSON result of an empty string
Prior to 1.9, an ajax call that expected a return data type of JSON or JSONP would consider a return value of an empty string to be a success case, but return a null to the success handler or promise. As of 1.9, an empty string returned for JSON data is considered to be malformed JSON (because it is); this will now throw an error. Use the error handler to catch such cases.
So, if remove the dataType
dataType: "json",
It works in jQuery 1.8.3 and 1.9.
An HTTP 204 response is not an empty string: it means there is no data. This is a valid response for delete and update operations.
This looks like a bug introduced in JQuery 1.9.
The reason removing the dataType property fixes this is because when it's set to "json" JQuery attempts to parse the content using JSON.parse and failing as a result. From the ticket:
This won't fail with any other dataType than "json" because the
regression is due to the re-alignment of parseJSON with native
JSON.parse (throwing an exception for null/undefined values).
Don't try the workaround suggested in the ticket of adding a handler for the 204 via the statusCode property, because both that handler and the error handler will be triggered. A possible solution is the following:
$.ajax(url, {
type: "DELETE",
dataType: "json",
error: function (error) {
if (error.status === 204) {
// Success stuff
}
else {
// fail
}
}});
I was having a very similar problem, and you helped my find my answer - so thank you. My solution, however is slightly different, so I figured I would share it.
As stated in the question, on the JQuery website it says:
Prior to 1.9, an ajax call that expected a return data type of JSON or JSONP would consider a return value of an empty string to be a success case, but return a null to the success handler or promise. As of 1.9, an empty string returned for JSON data is considered to be malformed JSON (because it is); this will now throw an error. Use the error handler to catch such cases.
I was passing JSON data to a method on my server with "void" as a return type because I did not need to do anything with returned data in the success function. You can no longer return null when passing JSON in an AJAX request in JQuery 1.9 +. This was possible in previous versions of JQuery however.
To stop getting an error and get the success function to fire instead, you must simply return valid JSON in your AJAX request. It doesn't matter what you pass, as long as it's valid, because (in my case anyways) you are not using the returned data.
The problem seems to be that jQuery treats the empty body (where Content-Length is 0) of a 204 response as "". Which is one interpretation, but the downside is that "" gets treated like any other response string. So if you have called jQuery.ajax() with the dataType:json option, jQuery tries to convert "" to an object and throws an exception ("" is invalid JSON).
jQuery catches the exception and recovers, but if you prefer to avoid the exception altogether (in your development environment) you might do something like the following. Add in the "converters" option to jQuery.ajax() and use it to change "" responses to nulls (I do this when dataType is json). Something like :
var ajax_options =
{
/* ... other options here */
"converters" :
{
"text json" :
function( result )
{
if ( result === "" ) result = null;
return jQuery.parseJSON( result );
}
}
};
var dfd = jQuery.ajax( ajax_options );