I have a function called login, when the User pushes the button, the code below will be executed.
So i try to see if the user exists and to get his data in an JSON Object but that doesn't work, i get following Message:
SyntaxError: Unexpected token s
at Object.parse (native)
the URL is exactly like i want it to be.
$scope.login = function() {
var request = $http({
method : "GET",
url : "/REST/user" + "/" + $scope.email + "/" + "password" + "/" + $scope.password,
headers : {
'Content-Type' : "application/json"
}
});
request.success(function(response) {
location.href = "../views/test.html"
});
request.error(function(response) {
growl.addErrorMessage("doesn't work", {
ttl : 4000
});
});
}
Output by Browser
{
"id": "9be1804a-e366-11e4-9d4b-82ea0d805d53",
"email": "test#gmx.com",
"facebook_id": null,
"firstname": "test",
"lastname": "blabla",
"password": null,
"gender": null,
"is_active": "0",
"birthday": null
}
This error is due to JSON.parse throwing an error when it encounters an object with key that doesn't start with quotes ".
For example:
{ abc: 123 }
would throw "Unexpected token a".
$http, by default, treats any data in response with "Content-Type": "application/json" or anything that starts with { or [ as JSON, and invokes JSON.parse.
Take a look at the response in the Network tab of the developer console to see what may have triggered it.
Related
I want to send a data like this :
{
"ad_title": "test",
"year": "2019",
"class": "Highline",
"files": [ 212]
}
To api in flutter. I tried to do that
var data = {
"year": selectedYear,
"class": _classController.text.toString(),
"files": json.encode(carfilesids),
};
final response = await http.post(url, body: data,headers:
{'Accept': 'application/json'});
However there's no errors in run time and when I print the value of json.encoder.convert(carfilesids) it gives me List, I got a response status code of 422 and it tells me " {"message":"The given data was invalid.","errors":{"files":["The files must be an array."]}} ". I also tried to json.encode the whole data but it goes wrong with the other data attributes.
You must use jsonEncode on your map, or else the http package will treat it as form data.
From the documentation:
If body is a Map, it's encoded as form fields using encoding. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.
final response = await http.post(url,
body: {
"ad_title": "test",
"year": "2019",
"class": "Highline",
"files": [ 212 ]
},
headers: {
'Accept': 'application/json'
}
);
Im trying to do a post request to GCP Natural Language for sentiment analysis.
When I try the data format on the code explorer on google it works fine but when I run it on a html page I get an error that reads
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"document[type]\": Cannot bind query parameter. Field 'document[type]' could not be found in request message."
},
{
"description": "Invalid JSON payload received. Unknown name \"document[content]\": Cannot bind query parameter. Field 'document[content]' could not be found in request message."
}
]
}
]
}
}
My code is:
<!DOCTYPE html>
<html>
<body>
<h1> Testing sentiment Analysis </h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var APIKEY = "AN API KEY";
$.ajax({
type : "POST",
url : "https://language.googleapis.com/v1/documents:analyzeSentiment?key="+APIKEY,
data : {
"document": {
"type": "PLAIN_TEXT",
"content": "Hello I am great"
},
"encodingType": "UTF8",
},
success: function(res) {
console.log(res);
alert(res['message']);
},
error: function(res) {
console.log(res['message']);
alert(res);
},
});
</script>
</body>
</html>
UPDATE:
A colleague has pointed me to the MISTAKE I was making. We have to use JSON.stringify() in order to send the request. The code should be like this:
$.ajax({
type : "POST",
url : "https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=YOUR-API-KEY",
contentType : "application/json; charset=utf-8",
data :
JSON.stringify({
"document": {
"type": "PLAIN_TEXT",
"language": "en",
"content": "Hola Victor"
},
"encodingType": "UTF8"}),
success : function(_result){
if (_result) {
alert('SUCCESS');
} else {
alert('ERROR');
}
},
error : function(_result){
}
});
I have tested it and it works.
I am working on my first node.js script which simply makes a http request to https://www.swapi.co/api/people/?search=Luke+ and parses the response data.
The endpoint is as follows:
var options = {
host: 'www.swapi.co',
path: `/api/people/?search=`+firstName+'+'+lastName
};
The logic is to get the data from response and parse it to a person object:
makeRequest(options, function( data, error) {
let person = data.results[0];
if (person) {
let height = person.height;
let response = person.name + " is " + height + " centimeters tall.";
callback(null, {"speech": response});
}
else {
callback(null, {"speech": "I'm not sure!"});
}
});
The definition of makerequest function is below:
function makeRequest(options, callback) {
var request = http.request(options,
function(response) {
var responseString = '';
response.on('data', function(data) {
responseString += data;
});
response.on('end', function() {
console.log('end: $$$' + responseString + '$$$');
var responseJSON = JSON.parse(responseString);
callback(responseJSON, null);
});
});
request.end();
}
When I run the script I got the error about parsing the JSON.
Unexpected end of JSON input
at Object.parse (native)
at IncomingMessage.<anonymous> (/var/task/index.js:42:37)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
I tested the endpoint using Postman and got the following JSON as response:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://www.swapi.co/api/planets/1/",
"films": [
"https://www.swapi.co/api/films/2/",
"https://www.swapi.co/api/films/6/",
"https://www.swapi.co/api/films/3/",
"https://www.swapi.co/api/films/1/",
"https://www.swapi.co/api/films/7/"
],
"species": [
"https://www.swapi.co/api/species/1/"
],
"vehicles": [
"https://www.swapi.co/api/vehicles/14/",
"https://www.swapi.co/api/vehicles/30/"
],
"starships": [
"https://www.swapi.co/api/starships/12/",
"https://www.swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://www.swapi.co/api/people/1/"
}
]
}
However, when I debug my code, the response data is an empty string. And that explains the JSON error.
What is wrong with my http request? Why am I not getting the correct response?
It appears that the API you are targeting only supports SSL, but Node's HTTP library only supports plain-text requests. Try using their HTTPS library instead.
var https = require('https');
var request = https.request(options, ...);
That URL you are using returns HTML by default.
Instead you need to call: https://www.swapi.co/api/people/?format=json&search=Luke+
(Note the format=json parameter)
I have the following JSON payload:
"app": {
"name": "myapp",
"version": "1.0.0",
"last_commit": {
"author_name": "Jon Snow"
"author_email": "my#email.com"
}
}
and the following .js file (using Mocha, Supertest and Should):
var supertest = require('supertest')
var should = require('should')
var server = supertest.agent('http://localhost:3001')
describe('GET /', function () {
it('should respond with JSON', function (done) {
server
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end(function (err, res) {
var payload = res.body.app;
payload.should.have.property("app");
payload.should.have.property("name");
payload.should.have.property("version");
payload.should.have.property("last_commit");
payload.should.have.property("last_commit.author_name");
payload.should.have.property("last_commit.author_email");
done();
});
});
});
When I test the app, I receive the following error message:
Uncaught AssertionError: expected Object {
"name": "myapp",
"version": "1.0.0",
"last_commit": Object {
"author_name": "Jon Snow"
"author_email": "my#email.com"
}
} to have property 'last_commit.author_name'
Why am I receiving an assertion error on the these lines?
payload.should.have.property("last_commit.author_name");
payload.should.have.property("last_commit.author_email");
Assertion is looking for a property called last_commit.author_name which is not present. You may want to break that into two assertions.
payload.should.have.property("last_commit");
let last_commit = payload.last_commit;
last_commit.have.property("author_name");
i'm tryng to request a (simple) flight-query trough google flight service via Apps Script
this is my code
function myFunction() {
var api_key = "XXXXXXXXXXXXXXX";
var url2= "https://www.googleapis.com/qpxExpress/v1/trips/search?key=" + api_key;
var param2 ={
"method" : "POST",
"contentType":"application/json",
"headers" : {"Content-Type": "application/json"
},
"request": {"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS","destination": "LAX","date": "2015-03-01"}]
},
muteHttpExceptions : true
};
try {
var response = UrlFetchApp.fetch(url2,param2);
Logger.log(response)
} catch (e) {
Logger.log(e)
}
}
this request send me error code
"error": {"errors": [{
"domain": "global",
"reason": "badRequest",
"message": "Invalid inputs: received empty request."
}
],
"code": 400,
"message": "Invalid inputs: received empty request."
}
The qpx Api is loaded in my developer console....anyone has any idea?
thanks in advance
Two things, the body of the request must be specified with the "payload" property, not "request", and you must actually convert your Javascript Object to a JSON string before posting it. (You also don't need the "headers" property, "contentType" will suffice, but I don't think it hurts anything)
var param2 ={
"method" : "post",
"contentType":"application/json",
"payload": JSON.stringify({"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2015-03-01"
}]
}
),
muteHttpExceptions : true
};
It's all documented here: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
However, the need to JSON.stringify() usually throws people off, if you pass a Javascript Object directly in the payload it is posted as form-encoded key/value pairs.
thanks very much...you put me in the right direction!
this is the right syntax:
var param2 ={
"method" : "post",
"contentType":"application/json",
"payload": JSON.stringify
(
{"request":
{"passengers": {"adultCount": 1},
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2015-03-01"
}]
}
}
),
muteHttpExceptions : true
};