UTF8 character encoding using node Request module - javascript

I have a simple app that uses a jquery ajax request to send form data to a node server, which in turn submits to a third party api using the Request module for node js.
The issue I'm having is that accented (and other similar) characters are not encoded correctly when they reach the third party server. For example é is recorded as é
I am fairly sure this is to do with the settings for Request as I get the same results when I bypass the ajax call.
Here are the settings I am using:
html:
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
jquery ajax settings:
type : 'POST',
url : '/api',
data : formData, // A json object
dataType : 'json',
ContentType : 'text/html; charset=utf-8'
Request module settings in node (there is nothing happening to the form data between ajax post and being sent by request):
request.post({
url: "https://testurl.com/api/",
form: formData,
headers: {'Content-Type': 'application/json; charset=utf-8'}
} ...
I have read various SO solutions but had no success, so any suggestions greatly appreciated.

After researching character encoding I discovered that the issue is to do with multibyte encoding of various characters (a quick google will find some good SO posts on the subject).
I thought it was odd that Request didn't handle this automatically, so I played around with the Request syntax and managed to fix the issue. Here is my revised code that works:
request(
{
url: 'https://testurl.com/api/',
method: 'POST',
json: true,
headers: {
'content-type': 'application/json'
},
body: formData
},
function (error, response, body) {
...
}
);

Related

React Native - Request with URL that includes credentials

So I have to make requests to various urls with different domains which contains credentials
I've successfully managed to send one like this:
const resp = await fetch(`my-url-here`, {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Authorization': `Basic ${base64.encode(my-key-here)}`
},
body: JSON.stringify(data)
})
However this works only for one domain while on the other I keep getting
[TypeError: Network request failed] on Android
[SyntaxError: JSON Parse error: Unexpected identifier "undefined"] on iOS (while executing the .json() method; I think the request is successful but with an empty response)
Every call on these domains work correctly using PostMan/ThunderClient
Any idea how to solve this?
Please share how you are processing response seems like request works fine but somehow there is an error while parsing the data into JSON.
invalid data contains in response which is not able to parse into JSON.

in Ajax, how to write "headers" for multiple condition?

as a beginner, I have some problems in using Ajax (with Discogs API) .. to get a discogs request token, discogs is saying
Include the following headers with your request:
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback"
User-Agent: some_user_agent
https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow
but, how to write this header?
below is my trying code, but I know this is not proper.
$.ajax({
type: "GET",
url: "https://api.discogs.com/oauth/request_token",
dataType: 'jsonp',
headers: {
ContentType: "application/x-www-form-urlencoded",
Authorization: OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback",
UserAgent: some_user_agent,
}
success: function (data) {
console.log(data);
document.getElementById("content").innerHTML += "<br>" + `${data}`;
},
error: function (error) {
console.log(error);
}
});
You said:
dataType: 'jsonp',
It isn't possible to specify headers for JSONP requests.
The API can't be using JSONP. Set the dataType to the format they are using.
The documentation says:
When you create a new application, you’ll be granted a Consumer Key and Consumer Secret, which you can plug into your application and start making authenticated requests. It’s important that you don’t disclose the Consumer Secret to anyone.
Putting those in your client-side code will disclose them to all your visitors.
The request to that end point should be made from server-side code.

Getting bytes when using axios

I'm sending post-request from front using axios
var data = {
key1: value1,
};
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios({
method: 'post',
url: 'my_url',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
data: JSON.stringify(data),
}).then(function (response) {
console.log(response);
});
But on django-backend I got bytes object b'{"key1":"value1"}'
Is there a way to get a json object on the backend? Or do I need to decode the request?
You don't need to use JSON.stringify with Axios. Axios handles it internally. Just send the plain javascript object to the backend like this
axios({
method: 'post',
url: 'my_url',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
data: data,
})
If you do use stringify, Axios takes that string as JSON and stringifies it again internally, that why you Django is not able to decode it.
EDIT
As per your comment on the question, I can see you are using a simple Django view to handle the request. Django views use WSGIRequest object as their request parameter. Because JSON is sent as the request body, they do nothing to it (do not parse) and present original data as it is. that's why you are seeing bytes object as request.body. You can manually parse it using json module from python standard library like this.
request.data = json.loads(request.body)
Or if you want more API compatible request object, I recommend using api_view decorator from Django rest framework like this
#api_view(http_allowed_methods=['post'])
def func(request):
pass
It will wrap your request with Request object from rest_framework.request module which will handle all parsing for you and present parsed data as request.data. You can read more about it here.

How to use transactional Cypher HTTP endpoint and new REST API Authentication and Authorization in Neo4j 2.2.x with JQuery

I'm looking for a code example creating a REST POST request with JQuery on Neo4j 2.2.x Transactional Cypher HTTP endpoint with new REST API Authentication and Authorization parameters.
Before Neo4j 2.2 version I used the Legacy Cypher HTTP endpoint (which is deprecated) to execute Cypher queries with the following code:
$.post("http://localhost:7474/db/data/transaction/commit",
{
"query": query,
"params": {}
}, "json")...
But I would like to move to 2.2 and use the transactional endpoint with user authentication parameters.
I can't find the right headers and parameters combination to use to create such a request. That's why I'm looking for a code example.
Best would be an example using a cross domain request but an example on same domain would be helpful too.
For authentication you need to supply an additional HTTP header to your request:
Authorization: Basic realm="Neo4j" <base64>
where <base64> is the base64 encoded string of username:password.
Not being a jquery ninja, but I guess the most simple way is to set the authorization header using ajax defaults:
$.ajaxSetup({
headers: { "Authorization": 'Basic realm="Neo4j' <base64>'}
});
When this default has been applied your $.post above should work.
The issue has been fixed in 2.2.0-RC01 and I can use transactional Cypher HTTP endpoint with authentication using the following example code:
$.ajaxSetup({
headers: {
// Add authorization header in all ajax requests
// bmVvNGo6cGFzc3dvcmQ= is "password" base64 encoded
"Authorization": "Basic bmVvNGo6cGFzc3dvcmQ="
}
});
$.ajax({
type: "POST",
url: "http://localhost:7474/db/data/transaction/commit ",
dataType: "json",
contentType: "application/json;charset=UTF-8",
data: JSON.stringify({"statements": [{"statement": "MATCH (n) RETURN n LIMIT 10"}]}),
success: function (data, textStatus, jqXHR) {
// use result data...
},
error: function (jqXHR, textStatus, errorThrown) {
// handle errors
}
});
Authorization means that the browser will send a preflight OPTIONS request which does not embed authorization headers.
This is most known as CORS.
Currently the Neo4j server do not reply to the OPTIONS request with the appropriate Access-Control-Allow-Headers.
This feature has been implemented in the source code and will be shipped with the GA release which I hope will come out this week.

ExtJS Ajax (JSON) post not working properly

I have seen a couple of examples from stackoverflow itself and also in the extjs documentation. But all I can see is 404 error.
Ext.Ajax.request({
url: '/project-desktop-service/decisions.json',
method: 'post',
headers: {'Content-Type': 'application/json'},
params: {
rolename: 'rolename'
},
success: function(){console.log('success');},
failure: function(){console.log('failure');}
});
I also have tried different combinations of removing and adding the content type, adding absolute url etc. But the result is the same failure everytime.
from Wiki :
The 404 or Not Found error message is a HTTP standard response code indicating that
the client was able to communicate with the server,
but the server could not find what was requested.
the only thing is not function right is you URL or you request somthing that was not ther.

Categories

Resources