Unexpected Token U Posting To Express [duplicate] - javascript

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

How to convert a Raw body data request for an API to ajax request

I am currently using postman to make an API request that pushes body data. I can get this to work either using "x-www-form-urlencoded" or "raw". See examples below:
I'm trying to convert this to an ajax javascript request but unsure on how to format the body/data text. Here is my script:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
headers: {
"Content-Type": "application/json"
},
data: {
" grant_type=client_credentials
&client_id=***
&client_secret=***
&resource=https://analysis.windows.net/powerbi/api "
},
success: (data) => {
console.log(data.token)
},
error: (data) => {
console.log('rr', data)
}
});
Any help would be appreciated
There's a mismatch here as you're setting the Content-Type header to JSON, yet you're sending form-urlencoded. You need to use one or the other consistently.
If you want to explicitly use JSON, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
contentType: 'application/json', // shorter than setting the headers directly, but does the same thing
data: JSON.stringify({
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***'
resource: 'https://analysis.windows.net/powerbi/api'
}),
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
If you want to use a form-urlencoded string, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: 'grant_type=client_credentials&client_id=***&client_secret=***&resource=https://analysis.windows.net/powerbi/api',
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
Note in the above examples that the first argument to the error handler is not the request or response data as your example seems to expect. I've amended that part to accept the correct arguments.

Call REST API in Jquery Ajax POST Method return 403 error

This below code is for calling a Login rest api through jquery ajax but it returns 403 error. I want to know if I missed any necessary parameter in ajax call or it's server side error. That source(HTML file) and destination(API) both in same cloud server.
But the api works fine in postman without any error
$.ajax({
type: "POST",
url: 'https://mzzzzcloudx.am.co.in/login',
dataType: 'json',
data: {
"login": "abcd#gmail.com",
"password": "12345"
}, //{"login":$("#login").val(), "password":$("#pass").val()},
contentType: "application/json",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "*"
},
success: function(data) {
console.log(data);
},
error: function(err) {
alert(err); //returns 403 error
console.log(err);
}
});
Do you try to remove the quote in the field names (login, password) of the data section?
data: {
login: "abcd#gmail.com",
password: "12345"}
And also, do you confirm that the field names (login, password) are the same in the REST method login()?

Issue sending json array via ajax to nodejs server

I'm sending via AJAX to my server nodejs, with this JS on client side:
function login(){
var array=[];
var jsonData={};
jsonData.user=$('#user').val();
jsonData.pass=$('#pass').val();
array.push(jsonData);
console.log(JSON.stringify(array));
$.ajax({
method:'POST',
url: 'auth',
dataType: 'application/json',
data: JSON.stringify(array)
}).done(function(msg){
alert( "Data Saved: " + msg );
});
}
As can you see, before send ajax, the browser output console is:
[{"user":"User001","pass":"SecretPassword"}]
On server side, I have this code:
router.post('/', function(req, res, next){
console.log(req.body);
// { '[{"user":"User001","pass":"SecretPassword"}]': '' }
console.log(JSON.parse(req.body));
// {"[{\"user\":\"User001\",\"pass\":\"SecretPassword\"}]":""}
res.sendStatus(202);
}
But, if I test this web service with Postman, my server receives Json data correctly:
Screen capture
Please, does anyone help me??, I trying solve this about 2 days :(
Don't stringify data, it's supposed to be an object, so you can send jsonData directly:
function login(){
var array=[];
var jsonData={};
jsonData.user=$('#user').val();
jsonData.pass=$('#pass').val();
array.push(jsonData);
console.log(JSON.stringify(array));
$.ajax({
method:'POST',
url: 'auth',
dataType: 'application/json',
data: jsonData // << here
}).done(function(msg){
alert( "Data Saved: " + msg );
});
}
var invoiceJson = {name: "abc"};
$.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(invoicejson),
success: (data) => {
try {
console.log( data);
} catch (err) {
console.log( err);
}
}
})

Uploading a file via Yammer API

I'm able to post a message but when I add either the attachment or pending_attachment, I get an error saying:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
yam.request(
{ url: "https://api.yammer.com/api/v1/messages.json" //note: the endpoint is api.yammer...
, method: "POST"
, data: {
"body" : document.getElementById("post_body").value,
"group_id" : document.getElementById("group_id").value
,"attachment1" : document.getElementById("attachment")
}
, success: function (msg) {
alert("Post was Successful!: " + msg.messages[0].id); //id of new message
}
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
);
} else {
yam.login( function (response) {
//nothing
});
}
});
}
yammer's javascript SDK doesn't work with attachment. (at least no working example has been seen on the internet) To upload an attachment, you can either upload the file to your server and then use og_url to post a link to that file on your server, or cook up your own ajax form upload. here is an example:
var data = new FormData();
data.append('body', document.getElementById("post_body").value);
data.append('group_id', document.getElementById("group_id").value);
data.append('attachment1', document.getElementById("attachment"), 'filename_of_your_choice');
$.ajax({
url: "https://api.yammer.com/api/v1/messages.json",
data: data,
beforeSend: function (xhr) {
// set authorization header
xhr.setRequestHeader("Authorization", "Bearer YOUR_AUTHORIZATION_TOKEN");
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log("ajax post success.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request.");
}
});
Notice that the authorization token is obtained in the response to a successful login. It is not your app ID. Also, I doubt document.getElementById("attachment") will work. You need to convert that object into an byte array blob.
It works for me:
function postAttach() {
var msg = $('#attach_body').val();
var m_data = new FormData();
m_data.append('body', msg);
m_data.append('group_id', 6194208);
m_data.append('attachment1', $('input[name=attachment1]')[0].files[0]);
yam.platform.request({
url: "messages.json",
contentType: "multipart/form-data",
data: m_data,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function (user) {
alert("The request was successful.");
},
error: function (user) {console.log(user);
alert("There was an error with the request.");
}
});
}
<div name="postYammer">
<input type="text" name="body" value="" id="attach_body" />
<input type="file" name="attachment1" id="attach_img"/>
<button onclick="postAttach()" type="button">Post</button>
</div>
//Example Nodejs in async function
// nota : you can get token from https://developer.yammer.com/docs/app-registration
const qs = require("qs");
const got = require("got");
const formData = require("form-data");
const fs = require("fs");
var json = {
is_rich_text: true,
topic1: 'tag1',
topic2: 'tag2',
body: 'body body',
group_id: 'group_id',
}
let querystring = qs.stringify(json);
var formData = new formData();
var aHeader = formData.getHeaders();
aHeader['Authorization'] = "Bearer token";
formData.append('attachment1', fs.createReadStream(path));
const response = await got.post('https://www.yammer.com/api/v1/messages.json?' + qs, {
headers: aHeader,
body: formData
});

Post JSON data along with id in Jquery AJAX

I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}

Categories

Resources