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
Related
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'm attempting to get a response from a Node application I created using the XMLHttpRequest object in JavaScript. The code I am using to do such is below:
var get = function()
{
var http = new XMLHttpRequest({mozSystem: true});
http.onreadystatechange = function() {
if (http.status === 200) {
console.log(http.responseText);
}
}
http.open("GET", "http://127.0.0.1:3000", true);
http.setRequestHeader("Content-Type", "text/plain");
http.send();
}
And the Node application is:
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) =>
{
let body = [];
req.on('data', (chunk) =>
{
body.push(chunk);
}).on('end', () =>
{
body = Buffer.concat(body).toString();
if(req.method === "GET")
{
console.log("GET");
}
res.setHeader('Content-Type', 'text/plain');
res.end("Hello World");
})
});
However, nothing is being printed. I opened the developer tools in Chrome and Mozilla and can see that the status is 200, and the response is listed under the response for the Ajax call - it says clearly "Hello World".
I'm doing this all locally, as a Node demo for school. I have the application able to handle post requests perfectly fine - but getting the response from the GET request does not seem to work. I'm open to any and all advice!
Thank you in advanced.
To answer my question, I was not aware that not having CORs enabled would cause such behavior - the browser would show that the request was going through, the response could be seen in developer tools, but could not be printed to console. Thank you to Jaromanda for helping me come to realize this.
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.
I am currently working with the Express platform, the Twilio Node.js SMS API and obviously javascript to send text messages to my users. Problem is, I don't know what I should do in order to send data through my GET variables on the front-end and capture those values with node.js on the back-end.
For testing purposes, I created a simple button that sends a text message to a fixed number when clicked.
Here is the javascript side:
function sms() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:5001", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
Here is the node.js side:
var accountSid = 'ACCOUNT_SID';
var authToken = 'ACCOUNT_TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
var express = require("express");
var app = express();
app.get('/',function(request,response){
var to = "TO";
var from = "FROM";
client.messages.create({
to: to,
from: from,
body: 'Another message from Twilio!',
}, function (err, message) {
console.log("message sent");
});
});
app.listen(5001);
I have came across two ways to send a responseText from Node.js, but can't manage to make them work
first one using response.send("Hello World"); or the second one response.write("Hello again"); response.end();
So just to sum it up, I want to send variables (to, from, message, etc.) through my http request, capture them in node.js and send a responseText! As a heads up, I'm very comfortable with AJAX requests between JS and PHP, but Node.js is new to me.
Thanks in advance
I think the new Guides will help you out here with How to receive and reply to SMS in Node.js:
https://www.twilio.com/docs/guides/sms/how-to-receive-and-reply-in-node-js
The CodeRail along the right hand side will walk you through it step-by-step but you should pay attention particularly to the section titled "Generate a dynamic TwiML Message".
var http = require('http'),
express = require('express'),
twilio = require('twilio'),
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function(req, res) {
var twilio = require('twilio');
var twiml = new twilio.TwimlResponse();
if (req.body.Body == 'hello') {
twiml.message('Hi!');
} else if(req.body.Body == 'bye') {
twiml.message('Goodbye');
} else {
twiml.message('No Body param match, Twilio sends this in the request to your server.');
}
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
http.createServer(app).listen(1337, function () {
console.log("Express server listening on port 1337");
});
Is it possible to POST data from a client javascript page to a node server (server.js) using an AJAX XMLHttpRequest()? What I am looking for is javascript code that will receive the data on the node server, specifically the values for member_nm ("newName") and member_email ("mail#google.com"). I control the server. I also understand that I can also use GET to send the text values by means of a querystring. Below is the request that is sent from the client javascript page by means of an event handler:
document.getElementById("btnAddMember").addEventListener("click", function()
{
var request = new XMLHttpRequest();
var path = "/Users/Admin/WebstormProjects/projectName/server.js";
request.onreadystatechange = function()
{
if ( request.readyState === 4 && request.status == 200 )
{
request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
request.open("POST", path, true);
request.send("member_nm=newName&member_email=mail#google.com");
}
};
});
You need to setup your server to accept this post request, the easiest will be to use Express with bodyParser middleware, like this :
var express = require('express');
var server=express();
var bodyParser= require('body-parser');
server.use(bodyParser.json());
server.post('/', function(req, res){
if(req.body){
// get the params from req.body.paramName
}
});
server.listen(8222, function(){
console.log('listening for requests ..')
});
In your client code change the 'path' to point to the server url:port, and I will put these outside of the onReadyStateChange:
request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
request.open("POST", path, true);
request.send("member_nm=newName&member_email=mail#google.com");
This is a working solution on how to POST variables from a client javascript file to a Node server using Express. The POST is initiated on the client by means of an event handler, btnAddMember. txtName.value and txtMembershipType.value contain the values to be posted. Note the syntax that is necessary to parse the values correctly. member_nm and member_type will be used to reference the properties on the Node server. First the client javascript:
document.getElementById("btnAddMember").addEventListener("click", function()
{
var request = new XMLHttpRequest();
var path = "http://0.0.0.0:0000"; // enter your server ip and port number
request.open("POST", path, true); // true = asynchronous
request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
var text= '{"member_nm":"' + txtName.value + '","member_type":"' + txtMembershipType.value + '"}';
request.send ( text );
});
Next is the server side code. Note that bodyParser must now be added to your project as a node_module. This can be done through the node program manager (npm). The POST statement basically parses the req.body from a JSON format to a javascript object format using a variable called 'member'. The code then logs the posted values for the two variables, member_nm and member_type. Finally a response status is sent to the client if the POST is successful.
var bodyParser = require("body-parser");
...
app.use(bodyParser.text({ type: "application/json" }));
...
// receive the POST from the client javascript file
app.post("/", function (req, res)
{
if (req.body)
{
var member = JSON.parse( req.body ); // parse req.body as an object
console.log("member_nm: " + member.member_nm );
console.log("member_type: " + member.member_type );
res.sendStatus(200); // success status
}
else
{
res.sendStatus(400); // error status
}
});