I've been having a problem all day sending json data via ajax to Express.
My ajax looks like this:
$('#saveClause').click(function () {
var username = document.getElementById('postUserName').innerHTML;
var clauseTitle = document.getElementById('modalTitle').innerHTML;
var clauseDescription = document.getElementById('modalDescription').innerHTML;
var clauseText = document.getElementById('modalText').innerHTML;
$.ajax({
url: "/classes/updateAssignment",
type: "post",
dataType: "json",
data: {
username: username,
title: clauseTitle,
description: clauseDescription,
text: clauseText
},
cache: false,
contentType: "application/json",
complete: function () {
console.log("complete");
},
success: function () {
console.log("success");
},
error: function () {
console.log("Process Error");
}
});
});
and my Express Classes routes looks like this:
router.post('/updateAssignment', function (req, res) {
console.log(req.body.username)
console.log(req.body.title);
console.log(req.body.description);
console.log(req.body.text);
res.type('json');
res.send({
some: JSON.stringify({
response: 'json'
})
});
});
I issued a postman post request to the url with this JSON object:
{
"username":"testing",
"title":"123",
"description":"j456",
"text":"seven"
}
and Express logged all the details in the console just fine, so it must be a problem with my ajax request as it's giving me an unexpected token u error but I don't know what's causing it. Any ideas?
Try removing the contentType: "application/json",
If you used postman with no headers, most likely this is causing the parser to fail.
Related
I am trying to make a post call through ajax from my front end to my express server, but I am getting the error net::ERR_UNKNOWN_URL_SCHEME. The code for ajax is below
function sendSteps(encodedLatLangs) {
$.ajax({
url: 'localhost:3000/route',
type: "POST",
dataType: "jsonp",
contentType: "jsonp; charset=utf-8",
crossDomain:true,
data: JSON.stringify({
steps: encodedLatLangs
}),
success: function (response) {
console.log(done);
},
error: function (request,error) {
console.log('Ajax call gave an error');
}
})};
My console is showing this.
This is how I am handling post request to this endpoint on backend
router.post('/route',function (req, res) {
console.log("Hello Received the Data");
res.send("Hello Received the Data");
//Doing something with the received data
});
Can some throw any light on this.
Thanks.
With JSONP you can sending only GET request (JSONP insert script tags into the DOM).
Your data should be a &key=value string and contentType is application/javascript
Try it:
function sendSteps(encodedLatLangs) {
$.ajax({
url: 'localhost:3000/route',
dataType: "jsonp",
contentType: "application/javascript; charset=utf-8",
crossDomain: true,
data: 'steps=' + encodeURIComponent(JSON.stringify(encodedLatLangs)),
success: function (response) {
console.log(done);
},
error: function (request, error) {
console.log('Ajax call gave an error');
}
});
};
Or use JSON (if you are a server owner and can set up CORS).
It can be done by setting "Access-Control-Allow-Origin" in response header.
Something like this. For more details visit https://enable-cors.org/server_expressjs.html
And also we have to remove "data type" and "content type" from the ajax request.
router.route('/route')
.post((req, res, next) => {
controllers
.post(req.body)
.then(data => {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.send(message.generateMessage(200, '', data))
})
.catch(err => next(err))
})
the overall code is a bit messy as I have been trying different things out and haven't gotten down to organizing them all. I am trying to send a PUT request to the /api/protected with the username and the new email to update the email. This is a protected route which needs the authtoken to access it which I have passed in. I am getting an unauthorized error.
function updateProfile(username, email, authToken, callback) {
const settings = {
url: '/api/protected',
data: {
username: `${username}`,
email: `${email}`,
headers: {
authorization: `Bearer ${authToken}`
},
},
dataType: 'json',
type: 'PUT',
success: callback,
error: error
};
$.ajax(settings);
}
This is the ajax request and now in the server side code:
app.put('/api/protected', jwtAuth, (req, res) => {
const updatedItem = User.update({username: req.body.username}, {$set:{email: req.body.email}})
return res.status(201).json({updatedItem});
});
If we look at the documentation, we see that the headers property should be on the settings sent to $.ajax, not within the data property. To remedy, simply move it out of the data property. For example:
function updateProfile(username, email, authToken, callback) {
const settings = {
url: '/api/protected',
data: {
username: `${username}`,
email: `${email}`,
},
headers: {
authorization: `Bearer ${authToken}`
},
dataType: 'json',
type: 'PUT',
success: callback,
error: error
};
$.ajax(settings);
}
Note that I've also cleaned up the indentation a bit to make it easier to see the correct placement.
In server side,I fetch data from database
var sql = require('mssql');
app.get('/api/comments', function(request, response) {
var sqlConfig = {
// Connection string parameters.
}
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = 'select TOP 10 * from comment';
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
sql.close();
response.json(recordset);
});
});
});
Then,I fetch the data from server side by AJAX (get method)
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
success: (comments) => {
this.setState({ comments })
}
});
I get an error when I get the data by Ajax.
(Uncaught TypeError: this.state.comments.map is not a function)
It seems that the data return is undefined.Instead of fetching database,the code is work if I use static data(hard code) in server side.
I think the problem is the callback function in sql.connect() but I have no idea how to solve it.Does anyone can help?
Error:
The solution is adding dataType: 'json' to the ajax
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
dataType: 'json',
success: (comments) => {
this.setState({ comments })
}
});
}
To all whom it may concern (I am really just trying to reach the "please add more detail" limit)
When passing data to the server as below the body is shown as empty.
Server
// POST method route
app.post('/pass', function (req, res) {
console.log("server received POST from homepage")
console.log(req.body)
res.send('POST request to the homepage')
})
Client
function ajaxJSONFunc(){
var inputData = document.getElementById('input2').value
var json = {"data":"abc"};
$.ajax({
url: "/pass",
type: "POST",
data: json
contentType: "application/json",
// dataType: "json", only use if you need to responce data to be JSON, if its not JSON an error will fire when uncommented. defaults to text
success: function(data) {
console.log("data passed back from server is:" + data)
},
error: function(err) {
console.log("an error occured")
console.log(err)
}
})
}
Works when passing like this (below), but I would prefer to send JSON data and not strings
$.ajax({
url: "/pass",
type: "POST",
data: inputData,
contentType: "application/x-www-form-urlencoded",
//dataType: "json", only use if you need to responce data to be JSON, if its not JSON an error will fire when uncommented. defaults to text
success: function(data) {
console.log("data passed back from server is:" + data)
},
error: function(err) {
console.log("an error occured")
console.log(err)
}
})
You defined contentType: "application/json". That's means you have to send a json object.
You have to use JSON.stringify() method.
data: JSON.stringify(json)
JSON.stringify function turns a Javascript object into JSON text and stores it in a string.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var json = "abc";
$.ajax({
url: "/pass",
type: "POST",
data: json,
contentType: "application/json",
// dataType: "json", only use if you need to responce data to be JSON, if its not JSON an error will fire when uncommented. defaults to text
success: function(data) {
console.log("data passed back from server is:" + data)
},
error: function(err) {
console.log("an error occured")
console.log(err)
}
});
});
</script>
</head>
<body>
</body>
</html>
I have JSON data sending to server. When I submit the for it is printing the data in console but not sending to the server.
It gives the following error
POST http://localhost:8080/rest/review/createReview 400 (Bad Request)
Here is my code
var promise = jQuery.ajax({
url: 'http://localhost:8080/rest/review/createReview',
type: 'POST',
data: '{myReview: myReview}',
dataType: "text",
contentType: "application/json",
success: function (data) {
console.log("Request successful", data);
},
error: function (data) {
console.log("Request failed", data);
}
});
It may be that your data is not valid JSON. Try:
data: JSON.stringify({myReview: myReview})