Send two JSON via same HTTP message - javascript

I have a Nodejs and d3.js programs which handle json data, send it via cross-domain and save a file. I have two JSON array which are: nodes and links. I need to save these into a file in another domain. In front-end side I am preparing http message like this,
function sendLinks()
{
jQuery(document).ready(function($)
{
$.ajax({
type:'POST',
url: 'http://192.168.80.143:2800/',
data:JSON.stringify(links),
contentType: "application/json; charset=utf-8",
dataType: 'json',
processData: false,
error: function(data)
{
console.log("error", data);
},
success: function(data)
{
console.log("success", data);
}
});
});
}
In the server side, I have the following code(nodejs)
app.use(function(req, res) {
//write a file
fs.writeFile('links.json', JSON.stringify(req.body), function(err) {
if(err) return console.log(err);
console.log('File created > links.json');
});
res.setHeader('Content-Type', 'application/json');
res.write('Message taken: \n');
res.end(req.body);
res.send("OK");
});
I want to do that for nodes JSON array in a different file name(e.g. nodes.json). How can I do that? Can I handle with the same http message?
Thanks,

Just return data: JSON.stringify({ links: links, nodes: nodes }), and unpack appropriately at serverside.

Related

Can't get JSON data from client side

I want to send JSON data from client side to server side.
Client side:
function send() {
var formData = {
firstname: $("#name").val(),
lastname: $("#lastname").val()
}
console.log("sending: " + JSON.stringify(formData));
$.ajax({
type: "POST",
contentType: "application/json",
url: "/dat",
data: JSON.stringify(formData),
dataType: 'json',
success: function(customer) {
console.log(JSON.stringify(customer));
},
error: function(e) {
alert("Error!")
console.log("ERROR: ", e);
}
});
}
Server side:
app.post("/dat", function (req, res) {
console.log(JSON.stringify(req.body)); // return undefined
res.end(JSON.stringify({ "nine": 9, "ten": 10, "eleven": 11 }));
});
I tried everything, but JSON.stringify(req.body) return only undefined. Sending data from server to client side working just fine...
Any suggestions?
You're resetting app here with:
var app = express();
Remove that line.

Alternative way of sending array to NodeJS using AJAX

So I've had a lot of problems with sending arrays to NodeJS using AJAX, when sending it with JSON, the error function always gets called (asking why that is has given me no answer that I could use).
So I was wondering if anyone knows a different approach to this, the one that I have right now is:
$.ajax({
type: 'POST',
url: 'http://localhost:1337/deposit?steamid=' + steamid,
contentType: "application/json; charset=UTF-8",
dataType: 'json',
data: JSON.stringify({arr:items}),
success: function(data) {
console.log("Tradeoffer has been sent");
},
error: function(data) {
alert("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
console.log("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
}
});
And on the server side:
app.post('/deposit', function(req, res) {
console.log('Deposit request recieved, info:');
console.log('STEAM ID: ' + req.query.steamid);
console.log('ITEMS: ' + req.body.arr);
});
So I was wondering if someone could tell me another way of sending an array.
If you can tell me what's wrong with this code, that would be awesome to of course.
app.js
//nodejs v4.2.6
var express = require('express');
var app = express();
var fs = require('fs');
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.get('/test', function(req, res) {
fs.readFile('test.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.post('/deposit', function(req, res) {
console.log('Deposit request recieved, info:');
console.log('STEAM ID: ' + req.query.steamid);
//console.log('ITEMS: ' + req.body.arr);
res.send({'finish':'finish'});
});
app.listen(3000, function(){
console.log('http Express server(worker) listening on port 3000');
});
test.html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
</head>
<body>
<script>
var steamid = 1;
$.ajax({
type: 'POST',
url: 'http://localhost:3000/deposit?steamid=' + steamid,
contentType: "application/json; charset=UTF-8",
dataType: 'json',
data: JSON.stringify({arr:[1,2,3,4]}),
success: function(data) {
console.log("Tradeoffer has been sent");
},
error: function(data) {
alert("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
console.log("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
}
});
</script>
</body>
</html>
I think that you listen to the wrong URL in Node. From AJAX you call url: http://localhost:1337/deposit?steamid=' + steamid,, but you listen to '/deposit' in Node.
You could try using RegExp:
app.post(new RegExp('/deposit?steamid=[a-zA-Z0-9]')
(assuming that `steamid only contains alphanumerical characters).
Since you're not sending a GET request you might as well get rid of the steamid parameter in the URL and call http://localhost:1337/deposit/' + steamid,; you should then listen to app.post(new RegExp('/deposit?steamid=[a-zA-Z0-9]') in Node.
Hope this helps!

Javascript AJAX SyntaxError: Unexpected token E in JSON at position 0 in ajax + node.js

I am making an AJAX POST request with multiple objects to a node.js server. Although my server sends status code 200, I am still getting the error Javascript AJAX SyntaxError: Unexpected token E in JSON at position 0. Here is my POST request:
var company_id = "some_generic_id";
var president = "obama";
var postData = {
company_id : company_id,
president : president
};
$.ajax({
type: "POST",
url: '/api/test_link',
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
data: postData,
success: function(data, status) {
console.log('it worked!')
},
error: function(request, status, error) {
console.log(request);
console.log(status);
console.log(error);
}
});
And here is my server side code:
app.post('/api/test_link', function(req, res) {
console.log('--post data--');
console.log(req.body);
/*
prints out:
--post data--
{ company_id: 'company_id', president: 'obama' }
*/
res.sendStatus(200);
});
Here's an image from my network tab:
Does anyone know what I might be missing or why my postData has invalid syntax?
The docs on ajax call states about dataType option:
The type of data that you're expecting back from the server. "json":
Evaluates the response as JSON and returns a JavaScript object.
Since you're not returning any data from the server, your empty data is parsed as JSON, which produces the error. Simply remove dataType: "json" if you're not returning any data.
add res.writeHead(200, {"Content-Type": "application/json"}); at the beginning of app.post('/api/test_link', function(req, res) { to specify that you wanted response as json format
Remove your
res.sendStatus(200);
Since res.writeHead(200, {'Content-Type': 'application/json'}); will also set your statusCode
So it would be like this
app.post('/api/test_link', function(req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
console.log('--post data--');
console.log(req.body);
/*
prints out:
--post data--
{ company_id: 'company_id', president: 'obama' }
*/
res.send();
});
I face this error if I'm not using JSON.stringify():
$.post(url, body, res => { ... });
// Error: {message: "Unexpected token e in JSON at position 0"}
$.post(url, JSON.stringify(body), res => { ... });

Send multiple variables to Node.js server with JQuery AJAX

When I try to log the data that was received by the server it is displayed as one long string. Instead I would like the received data to be seperable as different variables.
Client code
function sendData() {
var datas = { testdata: "TEST", testdata2: "TEST2" };
$.ajax({
url: 'server',
data: JSON.stringify(datas),
type: 'POST',
success: function (data) {
$('#lblResponse').html(data);
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
}
});
}
Server code
var http = require('http');
http.createServer(function (req, res) {
console.log('Request received');
res.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
req.on('data', function (chunk) {
console.log('GOT DATA!');
var receivedData = JSON.parse(chunk);
console.log(receivedData);
});
res.end("hello");
}).listen(1337);
I would like to be able to call for a single variable to get the value from it in the server. For example console.log(testdata); should display the value "TEST".
By stringifying your data object, you're sending a string to the server as the request body, and it's probably encoded using the "application/x-www-form-urlencoded" encoding.
You probably shouldn't JSON.stringify(datas), just use datas.
You need to parse the request body on the server. For that you could use a module like body

Node.js ajax post to mongodb

I'm having problem with sending data from ajax client to nodejs and storing that data in a collection in mongodb.
Here's my client code:
testdata = {'test1':'test1', 'test2':'test2'}
for(i=0;i<2;i++){ // for testing purposes
$(".btn").click(function(){
$.ajax({
url: 'http://localhost:8000/1',
type: 'post',
dataType: 'json',
data: testdata ,
success: function(){
console.log(i);
}
});
});
}
And my node.js server post handler with express:
app.post('/1', function(req, res){
db.collection('test', function(err, collection){
var data = req.body;
collection.insert(data, function (err, result) {
if(!err){
console.log(result);
}else{
res.end();
}
});
});
});
Body parser middleware is on, mongo is on of course, but my test collection is not receiving any data. I have a sence that i'm missing something very obvious here. Thanks for the help, much appreciated.

Categories