I have:
$http
url: '/api/v1/session/check'
method: 'POST'
data: sessionCheck
.success (response) =>
if response.authenticated is true
#user = response.user
deferred.resolve response
.error (data, status, headers, config) ->
deferred.reject data
throw {
data: data
status: status
headers: headers
config: config
}
And in my karma.conf.coffee, I have:
preprocessors:
'public/scripts/**/*.coffee': ['coverage']
'test/webapp/unit/**/*.coffee': ['coffee']
singleRun: true
reporters: ['story', 'coverage']
coverageReporter:
type: 'html'
dir: 'test/webapp/coverage/'
But when I run my test, I get an error saying:
ERROR [preprocessor.coverage]: Syntax error on line 59, column 8: unexpected '.' (\u002E)
56 : url: '/api/v1/session/check'
57 : method: 'POST'
58 : data: sessionCheck
59 : .success (response) =>
^^ :~~~~~~~~^
60 : if response.authenticated is true
61 : #user = response.user
62 :
Which, of course, makes no sense to me. Because if I change the code to:
$http(
url: '/api/v1/session/check'
method: 'POST'
data: sessionCheck
).success((response) =>
if response.authenticated is true
#user = response.user
deferred.resolve response
).error((data, status, headers, config) ->
deferred.reject data
throw {
data: data
status: status
headers: headers
config: config
}
)
then it works fine. Those 2 snippets of CoffeeScript compile to identical JavaScript, so what gives?
Are you using the latest karma-coffee-preprocessor?
Looks like your karma preprocessor uses outdated version of coffeescript (<1.7).
Method chaining without parenthesis was added only in 1.7, which came out not so long ago.
Related
This is driving me crazy!
Exactly the same POST request works fine in Insomina per screenshot below:
The only header Insomina has is: Content-Type: application/json.
Now, the same request in code (I even copied the code generated from Insomnia for axios) via axios in Typescript:
const saveReqConfig: AxiosRequestConfig = {
method: 'POST',
url: 'THE SAME URL USED IN Insomina',
timeout: 3000,
data: {
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
contentType: "application/json",
tags: '',
response: 'testing...',
type: 'VA',
},
headers: {
'Content-Type': 'application/json',
}
}
const normalAxios = axios.create();
const test = await normalAxios.request(saveReqConfig);
Don't understand why I am getting AxiosError: Request failed with status code 400 from code but the same request works fine in Insomina.
I think you did not set the headers correctly or you may not have setup the .create() properly.
Something like this:
const instance = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000,
headers: {
Content-Type: 'application/json' // <- set your headers
}
});
let res = await instance.request({ // <- pass the data here
data: { // This should be whatever you want to post to this url. I just copied what you had.
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
tags: '',
response: 'testing...',
type: 'VA',
}
});
Are you sure you need to use the .create() factory? The normal post like this might suite your needs better?
const data= { title: 'Axios POST Request Example' };
const headers = {
Content-Type: 'application/json'
};
axios.post('url', data, { headers }).then(response => console.log(response.data.title);
Posting here in case it helps someone.
It turned out that I couldn't post the request programmatically is because of lack of a TLS certificate. I didn't know that Insomnia has the option to disable the TLS and that's why it works in Insomnia.
To disable TLS (Do NOT do this in production!) from node with axios, create an instance of axios with a https agent setting rejectedUnauthorized to false e.g.
const instance = axios.create({
httpsAgent: new https.Agent({
rejectedUnauthorized: false
})
});
Also, set the environment variable as:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
I have a problem like this. I am new to react stuff. I used axios HTTP request npm package to write API call. But when I console log the response it says like this.
{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data:
error: {code: 101, type: "missing_access_key", info: "You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]"}
success: false
__proto__: Object
headers: {content-type: "application/json; Charset=UTF-8"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
__proto__: Object
It says that I am not providing API_key. This is how I have written my code.
const access_key ='my_key'
axios.get(`http://data.fixer.io/api/2013-12-24
? access_key =${access_key} & base = LKR & symbols = ETH`)
.then(res=>{
console.log(res);
})
Can Someone help me to solve this problem?. Thank You.
An alternative
In case you're feeling tired of using a quite long string url which easily causes mistakes, the axios library already supports an alternative. Using like this:
const access_key ='my_key'
axios.get('http://data.fixer.io/api/2013-12-24', {
params: {
access_key: access_key,
base: LKR,
symbols: ETH
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
For reference: https://github.com/axios/axios#example
I'm trying to update a boolean value using python eve, but I always receive the same error,
_issues: {deleted:must be of boolean type}
deleted: "must be of boolean type"
_status: "ERR"
I've tried sending the field as true (setting javascript type) 'True' and 'true' (as text) and 1, but the error is always the same.
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad¬e=&deleted=True
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad¬e=&deleted=true
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad¬e=&deleted=1
Any idea?
Regards
Gaston
settings.py
entity= {
'resource_methods': ['GET', 'POST'],
'schema': schema,
'datasource': {
'filter': {'$or':[{'deleted':{'$exists':0}},{'deleted':False}]}
}
}
schema = {
'name': {
'type': 'string',
'minlength': 1,
'maxlength': 50,
'required': True,
},
'code': {
'type': 'string',
},
'deleted':{
'type':'boolean',
'default':False
}
}
Full Request
Request URL:http://localhost:5000/campaign/532f797da54d75faabdb25d5
Request Method:PUT
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,no;q=0.6,es;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:112
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:5000
If-Match:3c7bc93e3c7d60da62f350ac990c16e29b08660f
Origin:http://localhost:5000
Pragma:no-cache
Referer:http://localhost:5000/static/index.html
X-Requested-With:XMLHttpRequest
Form Dataview parsed
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad¬e=&deleted=True
Response Headersview source
Access-Control-Allow-Headers:
Access-Control-Allow-Max-Age:21600
Access-Control-Allow-Methods:HEAD, GET, PUT, POST, DELETE, OPTIONS, PATCH
Access-Control-Allow-Origin:*
Content-Length:69
Content-Type:application/json
Date:Mon, 24 Mar 2014 00:30:10 GMT
Server:Werkzeug/0.9.4 Python/2.7.5
Set-Cookie:session=eyJfcGVybWFuZW50Ijp0cn
If you change your schema to coerce deleted value to bool, you can send int or str values and have it converted to bool on insert/update
First, create a function to convert whatever comes, to bool:
to_bool = lambda v: v if type(v) is bool else str(v).lower() in ['true', '1']
Then, change the deleted in the schema to use the function to coerce values, like this:
'deleted':{
'type':'boolean',
'coerce': to_bool,
'default':False
}
With this, you can per example send deleted with values such as '0', 0, 'false' or 'False' yelding to boolean false, or '1', 1, 'true' or 'True' resulting in true
This happens only when you send the request in the content type of form-data or application/x-www-form-urlencoded. In case of AJAX requests, sending boolean value works.
var payload = {
"deleted": false
};
var xhr = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(payload),
dataType: "json",
url: "some url"
})
Your payload should be a dict like:
payload = {"somebool": False}
then you convert it to a json string:
payload_json = json.dumps(payload)
which results in a lowercased bool value in a string:
'{"f5only": false}'
then you shoulc be able to post or patch it:
requests.post("{0}/endpoint/".format(api_server), headers=headers, data=payload_json)
how come when i'm clicking on the update button popup kendo grid , this error ocurrs?
The error in Firefox browser is in this form : SyntaxError: missing ; before d.0=value
and in Chrome browser : Uncaught SyntaxError: Unexpected number
I've uploaded a video regarding this error for elaboration n stuff
Jsfiddle Code
Video
Code
transport: {
read: {
url: 'https://dl.dropboxusercontent.com/sh/u9oxg5f6uweqh40/CbR3pNVg04/documentj',
dataType: 'json',
type: 'get',
cache: false
},
update: function(e) { return true; }
}
save: function (e) {
var that = this;
$.ajax({
url: '/echo/json',
type: e.model.id == null ? 'POST' : 'PUT',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(e.model),
success: function (data) {
// Alertify.log.success(data);
console.log('ok dadasaved');
that.refresh();
},
error: function (data) {
// Alertify.log.error(data);
console.log('no datasaved');
that.cancelRow();
}
});
}
You should provide more code to detect what's wrong with your code, but read this may help you:
Such error occurs when the transport definitions are inconsistent. In other words, if you would like to use custom transport method, all transport types should be defined as functions.
Having a standard read transport and custom update is not supported. Please configure all transports as functions and let me know if the error still occurs.
I had the same error and for me the problem was that the dataType option was not set for all transport methods. I marked that line with a comment below:
var linksDataSource = new kendo.data.DataSource({
transport: {
read: {
dataType: "json",
url: 'read-url',
type: "get"
},
destroy: {
dataType: "json", /* <============ THIS LINE WAS MISSING */
url: 'delete-url',
type: "delete"
},
update: {
dataType: "json",
url: 'update-url',
type: "post"
},
create: {
dataType: "json",
url: 'create-url',
type: "post",
complete: function () {
$("#searchResult").data("kendoGrid").dataSource.read();
}
},
/* ... */
I am trying to upload a file using Node and Google Docs REST API. I can upload the file just fine if I don't include the metadata, but it will always be uploaded as 'Untitled'.
But when I include the meta data I get the following error after sending my atom data and attempting to continue with the file upload:
ParseException - Content is not allowed in prolog
This is my first request to create an upload session and get a resumable-media-link
var meta = '<?xml version="1.0" encoding="UTF-8"?>'
meta+= '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:docs="http://schemas.google.com/docs/2007">'
meta+= '<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/docs/2007#document"/>'
meta+= '<title>Test</title></entry>'
var options = {
host: 'docs.google.com',
path: '/feeds/upload/create-session/default/private/full',
method: 'POST',
headers: {
'Host' : 'docs.google.com',
'Content-Length' : meta.length,
'Content-Type': 'application/atom+xml',
'GData-Version' : 3,
'Authorization' : 'GoogleLogin auth=' + authToken,
'X-Upload-Content-Type' : 'application/msword',
'X-Upload-Content-Length' : 31232
}
}
var req = https.request(options, function (res) {
// make 2nd request
});
req.end(meta);
This is what my 2nd request looks like after getting the resumable-media-link
var options = {
host: 'docs.google.com',
path: resumableMediaLink,
method: 'PUT',
headers: {
'Content-Length': data.length,
'Content-Type': 'application/msword',
'Content-Range': 'bytes 0-' + (data.length-1) +'/'+ data.length
}
}
var req = https.request(options, function (res) {
res.on('data', function (chunk) {
// ...
});
});
req.write(data);
req.end();
It seems like I am sending the atom data incorrectly. Any ideas of what I could be doing wrong?
I figured out what I was doing wrong.
I needed to set the 'Slug' header in the first POST request to initiate a resumable session.
I had it in the following request.