I am trying to make a private page dedicated to an Ajax request. Here is the simple request.
window.onload = loaded;
function loaded(){
var xhr = new XMLHttpRequest();
xhr.open('GET', '/data_annotations', true);
xhr.onload = function(){
if(this.status == 200){
var data = xhr.responseText;
console.log(JSON.parse(data));
} else {
console.log("Rip");
}
}
xhr.send();
//httpreq.abort();
}
Here is the node.js that it's running off of:
...
app.get('/', function(req, res, next){
console.log("Connected Successfully.");
res.render('home');
});
app.get('/data_annotations', function(req, res, next){
if(req.xhr || req.headers.accept.indexOf('json') > -1) {
const mc = mongo.MongoClient;
const url = 'mongodb://localhost:27017/';
const dbName = 'practiceMDB';
console.log("Got Data Annotations.");
mc.connect(url, { useNewUrlParser: true }, (err, client) =>{
if(err){
console.log(err);
} else {
const db = client.db(dbName);
data = db.collection('DataAnnotations');
data.find({}).toArray(function(err, data){
res.send(data)
});
client.close();
}
});
} else {
res.redirect('/');
}
});
app.listen(port, function(){
console.log('Server Started on Port '+port);
});
I only want /data_annotaion to run if it's from the Ajax request. If a user types in /data_annotations in the url, it should redirect them to the home page. When I ran this I got these results:
Server Started on Port 3000
Connected Successfully.
Connected Successfully.
This is indicating (to me) that the ajax request isn't registering as an ajax request, and is registering as a normal request. Further, I am getting this error:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
I believe it is due to the redirection. The Ajax request gets redirected, it takes the response of the home page and is unable to parse it (I believe this to be happening because it cannot parse HTML text or string text - don't quote me on that). How do I get Node JS to register my Ajax request?
PS: I looked at this answer to determine if a request is Ajax or not, but it always determines my requests as not Ajax: https://stackoverflow.com/a/28540611/6804700
First thing - In your client-side code you need to set the accept header, because that is what you are looking for in your server side code.
xhr.setRequestHeader("accept", "application/json");
Second you can use the following code to return the data as json in your server side code
res.json(data);
Another comment. It is bad practice to change the result type or redirect in an API. Your url is either returning JSON or redirecting to and HTML page which means the result is not consistent.
Related
I'm trying to get some information from the mongodb server to the frontend with ajax get request. Everything works fine except that if i try to call 5 times the javascript function, i dont get any response from my local server.
I tried to put some console.log() in order to debug in the nodejs function, it appears that the 6th time i call the function, the nodejs function doesn't even run.
javascript ajax front end code :
function addLike(music){
var request = new XMLHttpRequest();
request.open('POST', '/AddLike', true);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var myobj = {"music": music};
request.send(JSON.stringify(myobj));
setTimeout(function(){
$.ajax({
url: "/getAll",
type: 'GET',
dataType: 'json', // added data type
success: function(res) {
// => the 6th time i launch addLike(music), the function doesn't go there
update(res);
}
});
}, 200);
}
nodejs function :
app.get("/getAll", function(req, res){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("SoundShare");
var tab = dbo.collection('Musique');
tab.find({}).toArray(function(err2, result) {
if (err2) throw err2;
res.send(JSON.stringify(result));
db.close();
});
});
});
As you can see on the image below, in the console of firefox the last get ajax request doesn't receive any response.
.
.
It seems like it is a server side problem but i don't understand how to fix it.
Thank you in advance for your answer.
Your problem is that you are creating a new connection inside your /getAll function and the default poolsize is 5 as you can see in the docs.
You should be creating the connection when your node.js app starts up and use that connection throughout the application instead of creating a new connection on each request.
This question already has answers here:
How can I make an AJAX call without jQuery?
(24 answers)
Closed 3 years ago.
I'm setting up my first server with node.js, but I don't know how to connect a client and that server. I don't want to use jquery, and all the questions I could find about this involved jquery or were about different languages. Does anyone know how to do this?
Edit: I have a connection between the server and client, but the response has nothing in it. The code for my server is here, and the code for my client is here (in the folder "Multiplayer").
Do something like this to setup a Node.js HTTP server listenning on port 8080.
The client will send GET requests using AJAX.
index.html
<html>
<head>
<script>
var xhttp = new XMLHttpRequest();
// Create a function callback, called every time readyState changes
xhttp.onreadystatechange = function()
{
// When the response has been received with status 200
// Update the element div#response-holder
if (this.readyState == 4 && this.status == 200)
{
var txtDisplay = elem document.getElementById("response-holder")
txtDisplay.innerHTML = this.responseText;
}
};
// Send a GET request to /api, asynchronously
xhttp.open("GET", "/api", true);
xhttp.send();
<script>
</head>
<body>
<div id="response-holder"></div>
</body>
</html>"
server.js
// Load the http and fs (filesystem) modules
var app = require("http");
var fs = require("fs");
// Serve the "/index.html" home page on port 8080
app.createServer(function (req, resp)
{
fs.readFile("index.html", function(err, data)
{
resp.writeHead(200, {'Content-Type': 'text/html'});
resp.write(data);
resp.end();
}
);
}
).listen(8080);
// Also answer to GET requests on "/api"
app.get('/api', function(req, resp)
{
var responseStr = "Hello World!";
resp.status(200);
resp.setHeader('Content-type', 'text/plain');
return resp.send(responseStr);
}
);
Here is a W3Schools tutorial on AJAX:
https://www.w3schools.com/js/js_ajax_intro.asp
You may do that with vanilla JavaScript, using Fetch API.
Assuming that Node will provide you some URLs, you can get, post, etc., through fetching them.
More on how that works here:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
TCP connection between client and Node server will be the option. Here's a sample code snippet:
var ser = require('ser');
var clientSer = new net.Socket();
clientSer.connect(1220, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, Connection Established!');
});
clientSer.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
clientSer.on('close', function() {
console.log('Connection closed');
});
Node tutorial: https://www.w3schools.com/nodejs/nodejs_intro.asp
I'm new to using nodejs and javascript so I'm sorry if I'm just doing something obviously wrong. I have a nodejs app I'm running and serves a html page. That html page can send Post requests using XMLHttpRequest. The request goes though and my node app calls the function that my request is meant to invoke. The problem is I want to get some data back from that request so I am trying to get that from the response to the request. The issue is I am getting an empty response and I do not know why.
Here is my request.
function SendCachedTriangulation(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('responseLog').textContent = "sent triangulation: " + this.response;
}
};
xhttp.open("Post", "/sendCachedTriangulation");
xhttp.setRequestHeader("Content-type", "application/json");
var text = '{ "data" : ' + '{ "someData":"' + '1' + '" } }';
xhttp.send(text);
return false;
}
The result I get from this is response is empty. It does update the element I am trying to update but it just says "sent triangulation: ".
On the nodejs side this is my code.
router.post('/sendCachedTriangulation', (req, res, next) => {
client.SendCachedTriangulation(() => {
res.status(200)
;}, req.body
);
res.status(200).message = "sent triangulation";
res.send();
});
Which this seems to be calling my function to send cached triangulation properly i just don't get that "sent triangulation" message.
What do I need to change to display that message in my HTML page?
Actually I understood your snippet. I also understand that is complicated at first time with Node, because is everything Javascript. Let me explain: in your HTML, think the request is OK, but actually have, let's say, two files: HTML file, that performs the request, and the node HTTP server, that responds the request. So I mean something like:
// /server/app.js
router.post('/sendCachedTriagulation', (req, res, next) => {
res.status(200).send("sent triangulation")
})
// /client/index.html
client.SendCachedTriangulation(/* do stuff */)
I have a nodejs server and the code that I have as below. I send an AJAX request and I want the server to send me a response of a json data. When I put res.write()("string data like hello hello") in the server code, client side can take the value of inside and I can see the value on the console. But I cannot get json value with this function. I tried res.end() and res.send() functions as well but it didn't work. How can I send the json value and the following client side code can take the value correctly?
Server side,
app.use('/', function(req, res) {
console.log("req body app use", req.body);
var str= req.path;
if(str.localeCompare(controlPathDatabaseLoad) == 0)
{
console.log("controlPathDatabaseLoad");
mongoDbHandleLoad(req, res);
res.writeHead('Content-Type', 'application/json');
res.write("Everything all right with database loading"); //I can get this message
//res.end(json) I can not get json message with this function as well
res.send("OK");
//res.send(JSON.stringify(responseBody)); I can not get json message
}
Client side,
function loadDatabaseData()
{
console.log("loadDatabaseData");
var oReq = new XMLHttpRequest();
oReq.open("GET", "http://192.168.80.143:2800/load", true);
oReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
oReq.onreadystatechange = function() {//Call a function when the state changes.
if(oReq.readyState == 4 && oReq.status == 200) {
console.log("http response", oReq.response);
console.log("http responseText", oReq.responseText);
}
}
oReq.send();
}
I want to send an image from a nodejs server to another nodejs server.
I understand there are a lot of solutions, but I hoping to find out how to do it in the following way:
Server A (Sender)
Option 1
needle.post('http://127.0.0.1:8000', fs.createReadStream('test.png'), function(err, resp, body) {
});
Option 2
var reader = fs.createReadStream('test.png');
reader.pipe(request.post('http://127.0.0.1:8000'));
Server B (Receiver)
http.createServer(function(req, res) {
if (req.method === 'PUT' || req.method === 'POST') {
req.on('data', function(chunked) {
// I got nothing here
});
res.on('data', function(chunked) {
// I got nothing here
});
}
}).listen(8000, function() {
console.log('Listening for requests');
});
The problem is that if I read the file data that is sent over using fs.createReadStream, I am not able to receive any data from Server B.
[Edit] Also need to know how to handle the above using Express
You can try to create the fs.createWriteStream() and assign to req.pipe().
...
var saveTo = './test.png',
ws = fs.createWriteStream(saveTo);
ws.on('close', function () {
cb();
});
req.pipe(ws);
...
As mentioned by zangw in comments, the script actually works. My bad that my test.png is blank