Javascript & Node.js - make a JSON request - javascript

in this Question I read that in node.js you can distinguish between html requests and json requests like so:
app.get('/route', function (req, res) {
if (req.is('json')) res.json(data);
else if (req.is('html')) res.render('view', {});
else ...
});
now my question is how do you make a request that is interpreted as json in node server?
cause I tried with $.ajax and $.getJson and typed in the browser and all were html requests.
this is my request
$.ajax({ type: 'GET', url: "/test", dataType:"json", success: function(data){log(data)}})

The req.is method checks the incoming request type by inspecting the Content-Type header therefore you need to make sure this header is set in the request before it's sent up e.g.
$.ajax({
type: 'GET',
url: '/route',
contentType: "application/json; charset=utf-8",
....
});
However, the Content-Type header is used to determine the format of the request body, not the response. It's recommended you use the Accept header instead to inform the server of what type of format is appropriate for the response e.g.
app.get('/route', function (req, res) {
if (req.accepts('html')) {
res.render('view', {});
} else if (req.accepts('json')) {
res.json(data);
} else {
...
}
});
Then on the client, you don't need to worry about the Content-header but rather the Accept header, and jQuery already provides a handy little method for that
$.getJSON('/route', function(data) {
...
});

Try setting the contentType parameter
$.ajax({
type: 'GET',
url: 'your_url',
data: {
test: "test"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
....
});
EDIT:
You can use the request Module
all you have to do is
var request = require('request');
var options = {
uri: 'your_server_side_url',
method: 'POST',
json: {
"data": "some_data"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body.id) // Print the shortened url.
}
});
Check out that github link. May be that module will make your life easier

Related

HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

I'm trying to make a post with javascript using ajax to a spring controller
$("#crear").click(function () {
var user = document.getElementById("user").value;
var client = document.getElementById("client").value;
var documents = document.getElementById("documents").value;
if (user==null||client==null||documents==null){
document.getElementById("error").innerHTML='FALTAN COSASsssssssssss';
alert('Rellene todo los campos!')
}
const data={
fecha_inicio:'A',
id:'A',
fecha_entrega:'A',
usuario:{
nombre:user
},
cliente: {
nombre:client
}
}
$.ajax({
url: urlCrearAlta,
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data,
success: function(data) {
// ...
}
});
$.post(urlCrearAlta,JSON.stringify(data),function (data,satus){
console.log('${data} and status is ${status}')
});
document.getElementById("error").innerHTML=user+client+documents;
});
and java code
#RequestMapping("/altas")
#RestController
public class AltaRestController {
private AltaController altaController;
public AltaRestController(AltaController altaController) {
this.altaController = altaController;
}
#PostMapping("/create-alta")
public void createAlta(#RequestBody AltaDTO altaDTO) {
altaController.createAlta(altaDTO);
}
I'm getting the error Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
When i use $.ajax it does not send any request, just when i use $.post it send the request
The problem seems to be how you are using the $.post method. jQuery uses the application/x-www-form-urlencoded;charset=UTF-8 contentType on post by default if you don't specify another contentType. Combined with the #RequestBody annotation at backend (which requires application/json by default) it results in the seen exception and 415 status code.
The solution to this problem should be fairly easy, just add the correct configuration for the .post method, something like this:
$.post({
url: urlCrearAlta,
type: "POST",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data)
})
.done((data, status) => {
console.log(data, status);
//do whatever you like with data and status
});
Also, as stated in jQuery documentation here, $.post is just a shorthand method for $.ajax, so if $.ajax doesn't work and $.post does, there should be something wrong in how you configure the request or how you handle the callbacks methods. The major suspect for me would be the success function you specify in the $.ajax request, check there is nothing wrong in there, or just use the other callback methods, like .done, .fail and .always

jQuery .ajax POST request has an empty body when received by Node

For some reason when I make an ajax post using jQuery, the body, as received by node is empty. Here is my ajax post:
jQuery
var formData = {
'order': order,
'words': 'words'
};
$.ajax({
type: 'post',
url: 'https://example.com/charge',
processData: false,
data: JSON.stringify(formData),
contentType: 'json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
And here is my node code:
Node
app.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', routes);
routes/index.js
router.post('/charge', function(req, res) {
console.log(req.body);
} //This always logs {}
I have no idea what I could be doing wrong here. My browser even shows a payload and the post request (the formData object) but node logs nothing. Any ideas?
Use ajax request like this:
$.ajax({
type: 'post',
url: 'https://example.com/charge',
data: formData,
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
Mine was not working too, but solved by using,
contentType: 'application/json',
data: JSON.stringify(formdata),
Check following api
By setting the processData option to false, the automatic conversion of data to strings is prevented.
If you want to use json type, processData must be setted true
Jquery processData
This may be a late reply, but please also note the JQuery ajax documentation:
Object must be Key/Value pairs.
This took me 2 hours (server received empty body) because I was trying to post a more 'complicated' object.

Differentiate between HTTP request and Ajax request

I am currently working on ASP.NET WebApi and Angularjs
WebApi have a method
[System.Web.Http.AcceptVerbs("POST")]
[System.Web.Http.HttpPost]
public HttpResponseMessage SearchAddress(SearchDetails searchDetail)
{
//13.03993,80.231867
try
{
if (!WebSecurity.IsAuthenticated)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotAcceptable);
return response;
}
List<CollegeAddress> CollegeAddress = addressService.GetAddressFromDistance(17.380498, 78.4864948, 2000);
HttpResponseMessage responseData = Request.CreateResponse(HttpStatusCode.Accepted, CollegeAddress);
return responseData;
}
catch (Exception e)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
return response;
}
}
And I have to call this method from client side.
When I call this method using Ajax, it's not working, the method parameter searchDetail is always null if I use Ajax.
$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
type: "json",
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
But when I call that method via HTTP request, it is working.
$http({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
data: searchDetail,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
toastr.success('Account Created successfully!', 'Account Created');
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
Why? What is the difference between them? Why is Ajax not working and HTTP is?
jQuery's ajax() sends the data with Content-type: x-www-form-urlencoded.
Angular's $http sends the data with Content-type: application/json
Your server obviously expects JSON, but you set up the $.ajax() call incorrectly for that.
According to the docs:
The method property doesn't seem to exist.
The type property is supposed to determine the type of the request (e.g. 'GET', 'POST', etc.).
In order to change the default content-type to application/json you can use the contentType property.
I have not tried it myself, but something like this should work:
$.ajax({
type: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
contentType: 'application/json; charset=utf-8'
});
$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
I assume that searchDetail is an object. This is what the docs say about the data property:
... It is converted to a query string, if not already a string.
So if the server expects JSON then you have to convert it to JSON first:
data: JSON.stringify(searchDetail),
And as #ExpertSystem has pointed out you have to change method to type.
First you are duplicating the HttpPost, so just keep the second (and remove the namespace)
Second you want search detail to come from the body so decorate it with [FromBody]
[HttpPost]
public HttpResponseMessage SearchAddress([FromBody]SearchDetails searchDetail)
{

AJAX is not sending request

I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Categories