NodeJS Routes only work on localhost else theyre 404 - javascript

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

Related

ExpressJS and http(ajax?) call doesnt work?

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

app.get('') is not working in node js with query parameters

Iam trying to provide a new route for my conversation application where it should accept the parameters passed along with the route should be accepted and can be used in client side.But I couldnt figure out why basic .get() is not working ,where Iam unable to render the html.
'use strict';
var express = require('express'); // app server
var bodyParser = require('body-parser'); // parser for post requests
var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
var bodyParser = require('body-parser');
var app = express();
app.use(express.static('./public')); // load UI from public folder
app.use(bodyParser.json());
app.get('/:id',function(req,res){
var userid = req.params.id;
var pid = req.query.pid;
res.sendFile(__dirname,'/public/index.html');
});
module.exports = app;
On my localhost:3000 index file is getting loaded but for something like localhost:3000/3405?pid=CBM it is not loading.
Then I have a js file on client side which would require these two values id and pid.For now I just hardcoded.But how can I use these values to client side js file..Can someone help me how can I do this...
Thanks
Updated :Adding my client side js file
var Api = (function() {
var messageEndpoint = '/api/message';
var emp = {
"pid": "CBM",
"id": "3405",};
return {
sendRequest: sendRequest,
modifytext: function(intent, text) {
if (intent == "Hello") {
console.log(text, "Inside intent");
for (var key in emp) {
var tempKey = '{{' + key + '}}';
var tempValue = emp[key];
text = replace(text, tempKey, tempValue);
console.log("came back");
}
}
return text;
console.log(text,"Final text");
}
};
function replace(text, originalString, replaceText) {
console.log("Reached replace functions", text, originalString, replaceText);
if (replaceText)
text = text.replace(originalString, replaceText);
else
text = text.replace(originalString, "");
return text
}
}());
This is incorrect:
res.sendFile(__dirname,'/public/index.html');
It should be this:
res.sendFile(__dirname + '/public/index.html');
Or (a bit more robust):
const path = require('path');
...
res.sendFile(path.join(__dirname, 'public/index.html'));
As a side note: apparently, if you pass a directory name to res.sendFile(), it will send back a 404 response. Not sure that the rationale behind that is.

res.send is not a function

I am making an api call and recieving the data, however, I am having trouble sending the data back to my js file. I tried using res.send but I am getting an error. I can't seem to figure out how to send the information back to the javascript file. (I took my key out of the request link. For security reasons, however, I am getting the data back from the api call). The only problem I am having is returning the data to the frontend javascript file.
This is the Javascript file that sends the original request:
/ ********** options button function makes api call to get selected cities forecast *****************
function getCityForecast(e){
var id = document.getElementById('cities');
var getValue = id.options[id.selectedIndex].value;
var suffix = getValue + ".json";
var newObj = JSON.stringify({link : suffix});
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(newObj);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
console.log(xhr.response);
console.log('recieved');
} else {
console.log('error');
}
}
}
My server.js file looks like this:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');
var request = require('request');
// ****************** Middle Ware *******************
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
var retrievedString;
// **************** Post Request *******************
app.post('/', function(req, res){
var link = "http://api.wunderground.com/api/key/forecast";
retrievedString = link.concat(req.body.link);
request = http.get(retrievedString , function(res){
var body = '';
res.on('data', function(data){
body += data;
});
res.on('end', function(){
var parsed = JSON.parse(body);
console.log(parsed.forecast.txt_forecast);
res.send(parsed.forecast.txt_forecast);
});
})
.on('error', function(e) {
console.log("Got error: " + e.message);
});
});
app.listen(3000, function() { console.log('listening')});
You are overloading the definition of the variable res which is also what you called the response variable for your Express route handler method. In the callback function of the request, use a different name for that variable - for example:
request = http.get(retrievedString , function(resDoc){

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 extract zip from client in node

I'm having a node app which needs to get some zip file from client Postman and extract it to a folder in my fileSystem,Im using express I did the following which doesnt work,
what am I missing here?
I've created sample node app to simulate the issue.
var express = require('express');
var upload = require('multer')({ dest: 'uploads/' });
var admZip = require('adm-zip');
var app = express();
app.post('/',upload.single('file'),function(req,res){
debugger;
var zip = new admZip(req.file);
zip.extractAllTo("C://TestFolder//TestPathtoExtract", true);
res.send("unzip");
});
var server = app.listen(3001,function(){
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
})
This is how I use it im postman
If there is other way to do it with different open source this can be great!
I use
https://github.com/cthackers/adm-zip
which can be change to any other library
I've also find this lib but not sure how to use it with express
https://www.npmjs.com/package/decompress-zip
Thanks!
This is the set up I did for Postman, first this is my form-data body
Now in the header I left in blank after trying to set multipart/form-data manually and utterly failed, so no header here.
Here I did a pair of console.log, one of req.headers to be sure of Postman sending the right multipart/form-data and another of req.file
And well the output seems to be fine
Edit: the code.
var express = require('express');
var upload = require('multer')({
dest: 'uploads/'
});
var admZip = require('adm-zip');
var app = express();
app.post('/', upload.single('file'), function(req, res) {
console.log('%c > req.headers test.js [9] <=================================', 'color:blue;', req.headers);
debugger;
console.log('%c > req.file test.js [10] <=================================', 'color:blue;', req.file);
//instead of just req.file I use req.file.path as admzip needs the actual file path
var zip = new admZip(req.file.path);
zip.extractAllTo("/Users/myuser/Desktop/ext", true);
res.send("unzip");
});
var server = app.listen(3001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You need to pass filename as argument.
Use req.file.path
var zip = new admZip(req.file.path);

Categories

Resources