Semantic-ui / Search - Custom HTTP_ACCEPT - coffeescript

I'm doing a search module with Semantic-ui and I need to call a API in json:api format for my results. So i need to accept 'application/vnd.api+json' in the HTTP_ACCEPT header.
Is there a way to overload the header with a callback before the ajax request is sent ?
$('.ui.search')
.search({
type: 'recipe',
apiSettings: {
onRequest: (promise, xhr) ->
xhr.setRequestHeader('HTTP_ACCEPT', 'application/vnd.api+json')
url: '//staging-doeat.herokuapp.com/api/v1/recipes',
onResponse: (response) ->
console.log(response)
},
});
I would like to do something like this. But it doesn't work.
Thanks u for your responses.

Related

axios keeps removing question mark for query string

Here's my axios config:
const axiosApi = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL
})
axiosApi.interceptors.response.use(
response =>
response
,
error => {
if (error.response.status === 404) {
throw new Error(`404\nService does not exist\n${error.request.path}`)
}
}
)
export async function get(url) {
console.log(url)
return await
axiosApi.get(url, {
crossDomain: true
}).then(response => {
return response?.data
})
}
The problem is that when I try to get /path?key=value, I get the /pathkey=value does not exist error.
While console.log(url) shows me the true URL with the question mark and query string, the response interceptor strips the question mark out and that causes 404.
Any idea why this happens?
This is an Axios bug in v1.0.0
Issue reported here: https://github.com/axios/axios/issues/4999
Fixed in v1.1.0
You should pass the query params like below:
axios.get('/path', { params: { key: value} });
Try limit the version in dependency.
"dependencies": {
"axios": "~0.27.2",
},
may help.
Personally I don't even get why Axios developer decide to do this.
Basically according to HTTP Protocol both path and query parameters is considered URI.
Axios.get() should accept everything that is considered URI to conform with HTTP specifications.
And project which let user input its URL for fetch the data will just broken out of the box.

Sencha Touch: How to build a restful proxy url syntax?

Defined as a model and its associations, I wish the http calls to follow best practices of restful. For example, if I make the call
user.posts();
I wish to run a call http defined as
users/1/posts
If a call is then put on post with id 32 then the url of reference must be
users/1/posts/32
So I want to avoid using the filter property as is the default for a get
/posts.php?filter=[{"property":"user_id","value":1}]
This is because the api rest are already defined and I can not change them.
I would like to build a minimally invasive solution and reading on various forums the best way is to do an ovveride the method buildURL the proxy rest but was not able to retrieve all the data needed to build the final URL. Can anyone give me an example?
thanks
Try the following:
window.serverUrl = "192.168.1.XX"
var service = "login.php"
var dataTosend: {
username:"xx",
password: "yy"
}
var methode:"POST" / "GET"
this.service(service,methode,dataTosend,onSucessFunction,onFailureFunction);
onSucessFunction: function(res) {
alert("onSucessFunction"):
},
onFailureFunction: function(res) {
alert("onFailureFunction"):
},
service: function(svc, callingMethod, data, successFunc, failureFunc) {
Ext.Ajax.request({
scope: this,
useDefaultXhrHeader: false,
method: callingMethod,
url: window.serverUrl + svc,
params: data,
reader: {
type: 'json'
},
failure: failureFunc,
success: successFunc
});
I hope this will solve your problem...

Mootools Request.JSON returning null on iPhone

Sorry if this is a stupid question but I've looked everywhere and can't find an answer.
I'm using mootools 1.2.5 Request.JSON to make an ajax request to return json data. It works fine in all browsers and returns valid json data (validated at http://jsonlint.com and http://jsonformatter.curiousconcept.com), but when trying the same script on an iPhone and logging the response I get 'null' with the following error -- TypeError: 'null' is not an object.
Any suggestions are very much appreciated. Thanks.
Here's a simplified version of the the request only asking for limit and limitstart:
var jsonRequest = new Request.JSON({
method: 'get',
url: myurl,
data:{
'limit': 10,
'limitstart': 0
},
onSuccess: function( response ) {
if (/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
console.log(response); // returns 'null' on iphone - only one tested so far
}
//otherwise, returns valid json on all web browsers and continues fine
readMap( response );
},
onRequest: function () {
$('loading_div').style.display="block";
},
onComplete: function(){
$('loading_div').style.display="none";
}
}).get();
and here's a snippet of the response returned in browsers, but only returns 'null' on iPhone:
[{"street_address":"My Street Address","id":"2","short_description":"asdf","city":"Seattle","price":"234.00","formattedprice":"$234.00\/week","totalcount":"1"}]

How to get the REST response message in ExtJs 4?

I'm building upon RESTFul Store example of ExtJs 4. I'd like my script to display errors provided by the REST server, when either Add or Delete request fails. I've managed to obtain the success status of a request (see the code below), but how do I reach the message provided with the response?
Store:
var store = Ext.create('Ext.data.Store', {
model: 'Users',
autoLoad: true,
autoSync: true,
proxy: {
type: 'rest',
url: 'test.php',
reader: {
type: 'json',
root: 'data',
model: 'Users'
},
writer: {
type: 'json'
},
afterRequest: function(request, success) {
console.log(success); // either true or false
},
listeners: {
exception: function(proxy, response, options) {
// response contains responseText, which has the message
// but in unparsed Json (see below) - so I think
// there should be a better way to reach it than
// parse it myself
console.log(proxy, response, options);
}
}
}
});
Typical REST response:
"{"success":false,"data":"","message":"VERBOSE ERROR"}"
Perhaps I'm doing it all wrong, so any advice is appreciated.
I assume that your service follows the REST principle and uses HTTP status codes other than 2xx for unsuccessful operations.
However, Ext will not parse the response body for responses that do not return status OK 2xx.
What the exception/response object (that is passed to 'exception' event listeners) does provide in such cases is only the HTTP status message in response.statusText.
Therefore you will have to parse the responseText to JSON yourself. Which is not really a problem since it can be accomplished with a single line.
var data = Ext.decode(response.responseText);
Depending on your coding style you might also want to add some error handling and/or distinguish between 'expected' and 'unexpected' HTTP error status codes. (This is from Ext.data.reader.Json)
getResponseData: function(response) {
try {
var data = Ext.decode(response.responseText);
}
catch (ex) {
Ext.Error.raise({
response: response,
json: response.responseText,
parseError: ex,
msg: 'Unable to parse the JSON returned by the server: ' + ex.toString()
});
}
return data;
},
The reason for this behavior is probably because of the REST proxy class not being a first class member in the data package. It is derived from a common base class that also defines the behavior for the standard AJAX (or JsonP) proxy which use HTTP status codes only for communication channel errors. Hence they don't expect any parsable message from the server in such cases.
Server responses indicating application errors are instead expected to be returned with HTTP status OK, and a JSON response as posted in your question (with success:"false" and message:"[your error message]").
Interestingly, a REST server could return a response with a non-2xx status and a response body with a valid JSON response (in Ext terms) and the success property set to 'true'. The exception event would still be fired and the response body not parsed.
This setup doesn't make a lot of sense - I just want to point out the difference between 'success' in terms of HTTP status code compared to the success property in the body (with the first having precedence over the latter).
Update
For a more transparent solution you could extend (or override) Ext.data.proxy.Rest: this will change the success value from false to true and then call the standard processResponse implementation. This will emulate 'standard' Ext behavior and parse the responseText. Of course this will expect a standard JSON response as outlined in your original post with success:"false" (or otherwise fail).
This is untested though, and the if expression should probably be smarter.
Ext.define('Ext.ux.data.proxy.Rest', {
extend: 'Ext.data.proxy.Rest',
processResponse: function(success, operation, request, response, callback, scope){
if(!success && typeof response.responseText === 'string') { // we could do a regex match here
var args = Array.prototype.slice.call(arguments);
args[0] = true;
this.callParent(args);
} else {
this.callParent(arguments);
}
}
})

Facebook Javascript SDK response properties

Is there a list with all the properties I can ask using response after user was authenticated? like response.name, response.last_name and other? I would like to see a full list..
Include the line:
console.log(response);
in your Javascript. Then load up Firebug in your favourite modern browser and go to the console tab. You should be able to view the response as an object.
A full response object for you case should look like this:
{
status: 'connected',
authResponse: {
access_token: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}