how to send variable data from javascript to node js? - javascript

I want to send the variable from javascript to node js
here I am storing some data in my javascript variable
var roomurl = "this is the data";
And here is my nodejs code
app.post("/newcall", function(req, res) {
var n = (req.body.roomurl);
console.log("val"+ n);
});
I have included all the dependencies like express and body parser
but I am not how to send it
can I get help in my javascript code or
any Url from where I can get to now about how do
I send data from java script to node js ?
thanks

Actually, you should run the node/express application to a specific port, ex 3000
app.listen(3000, () => {
console.log('App running at 3000')
})
Then from your client you should post your data via Fetch API or another http client like this
fetch('http://localhost:3000/newcall', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({roomurl})
});

Related

node server cannot find the data in the body

i am sending a post request from fetch but the nodejs server is not able to access the body from the post request. I tried req.body but it just returns empty brackets.
const express = require('express');
const bodyParser=require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());
app.use(express.json());
app.get("/user",function(req,res){
res.send("just Checking");
});
app.post("/user", (req, res) => {
console.log(req.body);
res.send("got the data");
});
app.listen(3000,function(res){
console.log("server is workig a t local host 3000");
});
This is the browser side code
const checking = { name:"badmintion" }
function yo (){
fetch("/user",{
method : "POST",
Headers : {
'Content-Type':'application/json'
},
body: JSON.stringify(checking)
})
}
yo();
In the browser i can see that the data is being sent but i am unable to recieve the in the nodejs server it just shows empty brackets.
Edit: I was able to recreate the server code locally on my machine. I didn't find any issues. I used Postman to send the JSON to the /user route. The issue you might be having is in the front end.
Headers should be lowercase. You have capitalized it:
...
fetch("/user",{
method : "POST",
headers : {
...
}
...
Make sure you're sending data in a JSON format so that express can parse it into object:
To avoid any conflict for (parse json) better that remove body parser completely and try again.
For request, according to stanley, headers set as lowercase. Its will be work.
This tutorial maybe help u:
https://www.geeksforgeeks.org/express-js-express-json-function/amp/

How to get js file array to node js server?

I have one Javascript file linked to HTML and that js file is calculating an array on clicking submit button in Html and I want to get that data to node js file on post route without displaying it in HTML page. How should I do that?
Your nodeJS program is running on a server, which could just be your computer if you are using localhost, which means that it is in not connected to your HTML page. Therefore, you need to send the data from your js file via fetch request. In your nodeJS file, you need a route for receiving that data, which you create using express.
const express = require("express");
const {json} = require("body-parser");
const app = express();
app.post("/submitData", (req, res) => {
const data = req.body;
console.log(data);
res.status(200).json({"Message": "Data posted", data});
})
app.listen(3000,() => {
console.log("Server running on port 3000");
})
Now, in your javascript file, you need a fetch request.
fetch(http://localhost:3000/submitData, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response => {
return response.json();
}).then(data => {
console.log(data)
})
This should do the trick. I would also suggest you download Postman, which is great for testing APIs and trying out http requests
I forgot to point out, after doing:
const app = express();
you should put:
app.use(json());
I apologise for the mistake, it should remove the error you mentioned in the comment.

Client program for continuous talking to an echo server in nodejs

I'm an absolute beginner in nodejs. I've created an echo server in nodejs. And honestly i would say, i followed few youtube tutorials for this. There is nothing wrong with the server code. I want to create a client program to talk to this server. I dont want to use telnet client or any such thing. And by 'continuous' I mean the server and client should stay connected till I close the server manually using ctrl+c. Here's my server.js.
const express = require('express');
const bodyParser=require('body-parser');
var server=express();
server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());
server.post("/", function (req, res) {
console.log("I got: "+req.body.message);
res.send(req.body.message);
});
server.listen(3000, function() {
console.log("Express echo server is listening on port 3000");
})
I do not say hey write the code for me. In fact I tried also. Here's my client.js
var request = require('request');
var arg="";
process.argv.slice(2).forEach(function (val, index, array) {
arg+=val +" ";
});
request.post({
url: "http://localhost:3000",
json: true,
body: {message: arg}
}, function (err, response, body) {
if(!err && response.statusCode==200) {
console.log(body);
}
});
But client sends data only once that too using command line argument.
node client.js hello
PS: I'm using these npm modules express, body-parser and request
What you made is a HTTP Server using express.
The server runs alright, but the client closes because you are only making a single request to the server. So what is happening is expected behaviour.
So, there are multiple ways,
The most simple way would be, using readline or some other to continuously read the lines that you type And sending it to the server:
const request = require('request');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
readline.setPrompt('msg: ');
readline.prompt();
readline.on('line', function(input) {
if(input === 'close') return readline.close();
request.post({
url: "http://localhost:3000",
json: true,
body: {message: input}
}, function (err, response, body) {
readline.prompt();
});
}).on('close', function() {
console.log('Closed');
process.exit(0);
});
But the proper way would be using sockets like socket-io to make a persistent connection between the server and client. Read here for more information.

Unable to make a GET request with AJAX under Node.js when using NGINX

Despite I have learned and implemented AJAX request with Node on my local server. I am finding that the requests that I created on my local server, just does not work at cloud server.
When I use AJAX to request data to the server (Node), the request does not get to the server because of the URL (or I think so).
Node Code:
app.get("/",function(req,res){
app.use(express.static(__dirname + '/'));
app.get("/mypath/",function(req,res){
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data);
});
});
Javascript Code:
$.ajax({
url: 'http://localhost:3000/mypath/',
type: 'GET',
data: {//some data to use on the server},
dataType: "json",
complete: function(data){
//some stuff with the transformed data
},
});
The code above works in the local server (my pc). But not in the cloud one, I had some problems trying to the server static files with NGINX and Express, but I was able to figure it out.
Do you think that given the way I am serving the static files and that I am working in the cloud server, I should use AJAX request in a different way when we are trying to communicate through an URL?
Console Log:
Console Log after using Marcos solution
EDIT: Code from jQuery AJAX and Node Request
Node Set-Up:
var express = require('express');
var app = express();
var request = require("request");
var db = require('mysql');
const path = require('path');
var http = require("http").Server(app);
var io = require("/usr/local/lib/node_modules/socket.io").listen(http);
http.listen(3000, 'localhost'); //At the end of everything between here and the code.
GET Node Code:
app.use(express.static(__dirname + '/'));
app.get('/reqData',function(req,res){
//I never arrive here
console.log("print that I am here");
transform(req.query.selection1,req.query.selection2,function(){
res.json(data); //data is transformed globally
});
});
Ajax:
function requestData(){
$.ajax({
url: 'http://localhost:3000/reqData',
type: 'GET',
data: {//Some stuff to send},
dataType: "json",
complete: function(data){
do(data);
},
error: function(e){
console.log(e);
}
});
}
New Console Log:
Chrome Console Error
The main issue you have, is how you're defining your routes, you will be unable to reach /mypath/ until you perform a request first to /.
You should not define your routes that way, each route should be defined individually, and not in a nested way.
app.get('*', (req, res, next) => {
// Set your cookies here, or whatever you want
// This will happen before serving static files
next(); // Don't forget next.
});
app.use(express.static(__dirname + '/'));
app.get('/mypath/', (req,res) => {
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data); // make sure it is defined.
});
And your route app.get('/') conflicts with express.static(__dirname + '/'), so you should just remove it if you're only serving an index.html file, which seems to be your case.
Then in your $.ajax you should add the protocol to the URL.
$.ajax({
url: 'http://yourdomain.com/mypath/',
// url: 'http://localhost:3000/mypath/',
/* ... */
});
Now, supposing you have everything else setup correctly, you will be able to access /mypath

Request data using jQuery from a NodeJS server

I have the following client code (that runs in a browser or atom-shell/node-webkit Web API):
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1:1337/users',
type: 'GET',
dataType: 'json',
success: function(res)
{
console.log(res);
}
});
});
Pretty simple stuff, it requests a list of users in JSON format from a server.
Now on the server end (Node API) I have the following code:
var http = require('http');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'admin',
password : 'qwe123'
});
// Create the server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is just a placeholder for the index of the server.');
}).listen(1337, '127.0.0.1');
// Build a response
http.get('http://127.0.0.1:1337/users', function(res) {
var json = { 'status' : res.statusCode, 'response' : res };
JSON.parse(json);
}).on('error', function(e) {
var json = { 'status' : e.statusCode, 'message' : e.message };
JSON.parse(json);
});
I've become confused as how to create the server and then effectively create endpoints (e.g. /users) that I can talk to via my client code.
1.) Am I right in thinking that http.get only gets data from an already established endpoint? And that createSever actual creates the endpoints? Or is there another shorthand method for creating these endpoints after the server has been created? So basically that get request isn't required in this example as I am wanting to request it client side.
2.) In any case I need to create this endpoint /users and return the following:
connection.connect();
connection.query('SELECT * FROM users', function(err, results) {
JSON.parse(results);
});
connection.end();
Can anyone help point me back in the right direction? Seems like I've missed that part in the docs where you can create the different endpoints on your server.
I am afraid you are mixing expressjs and node http module. If you are just using node "http", refer this: Nodejs to provide 1 api endpoint e one html page on how to achieve the routing of URL's.
All said, i would suggest you to take a look at the library expressjs for this: http://expressjs.com/starter/basic-routing.html. It largely simplifies the route management and provides much more functionality.
Hope this helps you.

Categories

Resources