ExpressJS and http(ajax?) call doesnt work? - javascript

im trying to do a simple ajax call but somehow it doesnt work.I cant figure it out, would be nice if someone could help me.
Server script :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
//listen to smth
app.get('/test1', function (req, res) {
res.send('GET request to the homepage');
});
//start server
app.listen(port);
console.log("Server running on port" + port);
HTML Button that runs a client based JS
<button onclick="callServerSideScript('key','port','address','username','password','gem','proxy','crypt')" type="button" id="build">Get build</button>
Client based JS :
function callServerSideScript(key,port,address,username,password,gem,proxy,crypt){
keyVal = document.getElementById(key).value;
portVal = document.getElementById(port).value;
addressVal = document.getElementById(address).value;
userVal = document.getElementById(username).value;
pwVal = document.getElementById(password).value;
gemVal = document.getElementById(gem).checked;
proxyVal = document.getElementById(proxy).checked;
crytpVal = document.getElementById(crypt).checked;
httpRequest = new XMLHttpRequest();
httpRequest.open('POST', '/test1');
httpRequest.send('some data');
}
Normally it should do a /test1 request to the server and the server should react to it? I am missing something?

eighter do httpRequest.open('GET', '/test1'); (client) or app.post('/test1', handler); (server). but if your sending a POST request and the server expects a GET request it just gets 404'd

Related

NodeJS Routes only work on localhost else theyre 404

I'm trying to create a simple website with Node.js! I installed node.js on the server,i set up DNS and started my server. On a button click a POST HTTP request "/buildRequest" should be sent to the server. Inside this route, an external function should be called that returns an Object containing an
ErrorMessage(an Object like error:"this is an error") or an path(string) to a file.It works perfectly fine if I go on the page via localhost:8888(port i'm using). The route will get called. But if i go on the website with the DNS name and click on the button the page says :
"Failed to load resource: the server responded with a status of 404 (Not Found)"
Server.js
var express = require('express');
var bodyParser = require("body-parser");
var dbFunc = require("./dbFunctions.js");
var util = require('util');
var app = express();
var path = require('path');
var fs = require('fs');
var port = 8888;
var http = require('http');
http.globalAgent.maxSockets = 1000;
//allow to use body-parser
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
//allow to use static files
app.use(express.static("public"));
//listen to smth
app.post('/buildRequest', function (req, res) {
//buildrequest call was succ
var main = dbFunc.main(req.body.dbParameter, function (data) {
var result = data;
res.send(result);
});
});
//start server
app.listen(port);
console.log("Server running on port" + port);
My client side js function that get triggerd when clicking a specific button :
function callServerSideScript(dbParameter) {
//do check here if a value is missing
db = document.getElementById(dbParameter).value;
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', '/buildRequest')
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("dbParameter=" + db);
httpRequest.onload = function () {
if (this.status >= 200 && this.status < 400) {
try {
//if try is successfull response is an object. Return the object as string(error message)
var test = JSON.parse(this.response);
alert(this.response);
} catch (error) {
//is not an object,means its a string = download
window.open("/download");
}
} else {
// We reached our target server, but it returned an error
}
};
httpRequest.onerror = function () {
// There was a connection error of some sort
};
}
Why does the route work with localhost on the server but not "remote" when accessing the website outside the server?
EDIT :
My folder structure looks like this :
main.js containing client side functions(like doing the HTTP request)
.
+--public
| + index.html
| + <someother html files>
| + main.js
|
+-- server.js
|
|
+-- dbFunctions.js
Greetings

Pass a parameter to another JavaScript and run the script

Send a parameter(URL) from another script through recursion to this script.
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var murl = 'mongodb://localhost:27017/getData';
url = '';
app.get('/getData', function(req, res){
firstCall(req,res)
//console.log("cookie",req.cookies);
})
var firstCall = function(req, res, data){
console.log("URL: ", url);
res.send('Check your console!');
}
app.listen('3000')
console.log('Magic happens on port 3000');
module.exports = function(app) {
app.get('/getData', function() {});
};
I want this code to act as backbone or logic board. And some other file should be able to trigger this logic board file by adding the URL to this file.
Like we pass parameters to function to call. How do I do it here.

Send/receive data from Javascript to Node.js using Express

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");
});

How to send post request to server.js in cloud9

Hi I'm learning the mean stack on cloud9.
I've come to the point where I'm trying to send variables to my node.js server but I'm not sure if my server is picking it up. Are there any obvious errors with my post request code?
app.js(frontend angular)
console.log('begin');
var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", "https://new-backup.splacorn.c9.io/myApp/server/server.js/", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
console.log('onreadystatechange');
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
else {
console.log('readyState=' + http.readyState + ', status: ' + http.status);
}
}
console.log('sending...')
http.send(params);
console.log('end');
this is the console response that I am getting:
begin
sending...
end
POST https://new-backup.splacorn.c9.io/myApp/server/server.js/ net::ERR_INSECURE_RESPONSE$scope.addNewUser
onreadystatechange
readyState=4, status: 0
I believe that the error that I am getting is attributed to this line:
http.open("POST", "https://new-backup.splacorn.c9.io/myApp/server/server.js/", true);
once http.send(params); calls it.
Here is the server.js file (backend)
var express = require('express');
var fs = require('fs');
var app = express();
var bodyParser = require('body-parser')
app.use(express.bodyParser());
app.post('/', function(req, res){
console.log('POST /');
res.writeHead(200);
res.end('this is from the server');
});
var port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port);
Does anyone know why I'm getting the error? Part of me thinks that I'm getting the cloud 9 server url wrong but I'm not sure... If anyone can help me figure this out that would be amazing!
I'd like to use socket.io instead.
Here's a small example of how you can do it:-
Client side code:
var io = io("http://localhost:1337");
io.emit('give me some data',{test:'testing socket.io'});
io.on('got the data',function(data){
console.log(data.test);
});
Server side code:
var app = require('express').createServer();
var io = require('socket.io')(app);
io.on('connection',function(socket){
socket.on('give me some data',function(data){
socket.emit('got the data',data);
}
app.listen(1337);
You can get socket.io here
They have both client side as well as server side code. Hope you got my point. I was at phone so couldn't type much. And also, socket.io provides real time connection between the client and the server :)

AJAX POST JSON from javascript to nodejs server

I'm trying to send a JSON object from javaScript to node.js server. I'm using a standard XMLHttpRequest to send it from javascript and a standard node.js code.
Two codes seem to be communicating normally however the node.js always gives me an empty JSON object. I'm not really sure what am I doing wrong.
This is my javascript code:
<html>
<head>
<script>
function xhrPost() {
var data = {"name":"John", "time":"2pm"};
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://[serverIP]:8080/addUser");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));
}
</script>
</head>
<body onload="xhrPost()">
</body>
</html>
and this is my node.js code:
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/addUser", function(request, response) {
console.log(request.body); // this line allways produce {}
response.send("Message received.");
response.end();
});
app.listen(8080);
You have to use myParser.json() as a middleware. See more about it in https://github.com/expressjs/body-parser#bodyparserjsonoptions
After following line:
var myParser = require("body-parser");
You should add on more line as:
var myParser = require("body-parser");
app.use(myParser.json());// parse application/json
This was the most helpful stackoverflow page to solve my problem as well.
I was trying to get form fields, formulate them into a JSON on the client, then send to the server to use the fields for a MySQL call to a separate database.
Object {name: "", reps: "1", weight: "1", date: "", lbs: "0"}
I was able to get the object logging correctly on the client, yet every time I tried to send the data to the server,
console.log(req.body);
Would always return on the server as either
{}
undefined
Server side my setup with functioning data passing is
var express = require('express');
var mysql = require('./dbcon.js');
var app = express();
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
var request = require('request');
var myParser = require("body-parser");
var async = require('async');
app.set('view engine', 'handlebars');
app.set('port', Number(process.env.PORT || 3000));
app.use(myParser.json());
app.use(express.static('public'));
app.engine('handlebars', handlebars.engine);
On my client side js file, I have a function upon form submit that does:
var data = {
"name":document.getElementById("fname").value,
"reps":document.getElementById("freps").value,
"weight":document.getElementById("fweight").value,
"date":document.getElementById("fdate").value,
"lbs":bool
};
...
req.open("POST", "/insert", true);
req.setRequestHeader("content-type", "application/json;charset=UTF-8");
...
req.send(JSON.stringify(data));

Categories

Resources