Am I missing a package? - javascript

I have written the following code so far:
var http = require('http');
http.createServer(function (request,response) {
homeRoute(request, response);
}).listen(1337);
console.log('Server running at http://<Dans-Laptop>/');
function homeRoute(request, response) {
//response.writeHead(200, {'Content-Type': 'text/plain'});
//response.write('Header\n');
//response.write('Search\n');
//response.end('Footer\n');
//response.end('Hello world\n');
//if url == "/" && POST
//redirect to /:username
The problem I'm having is that as soon as I enter "function homeRoute(request, response) { and run the Server.js file from the CMD I get a SyntaxError: Unexpected token > at exports.runInThisContext etc..
If I blank out that line using // everything up until there is working fine i.e the server starts running at http:///
What is the problem with the last bit of code? Am I missing a package?

I have answered this query.. changed the port to 3000 and it appears to be fine!
Thanks.

Related

HTTP/HTTPS Nodejs Serve Javascript with HTML

I have a very simple https Nodejs server that serves an index.html that includes a request for a Javascript file. I cannot seem to get the browser to recognize the Javascript file.
<html>
<head>
<script src="deviceMotion.js"></script>
</head>
<body>
</body>
</html>
For this example, the contents of deviceMotion.js are immaterial. When I load the page and check Crhome debug tools, I receive a syntax error in the first line of the Javascript file, saying
Uncaught SyntaxError: Unexpected token '<'
I look at the "javascript" file's contents only to see that it is exactly the same as my index.html. This leads me to believe that there is an issue with the way my Node HTTPS server is serving the Javascript. Likely, it is just serving the html twice, even though my console logs show 3 separate requests being made, and only 2 when I remove the script tag from index.html. Obviously, it is trying to request the Javascript file, but there is something not right.
Here is the code for my server app.js
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
console.log("request received");
console.log(req.headers.referer);
fs.readFile('./src/index.html', function (error, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
My files are structured such that I have app.js in the same directory as a folder called "src" and I have index.html and deviceMotion.js under src.
How can I control what files I serve and when depending on incoming requests? How can I differentiate requests made in order to serve the right file? I have tried parsing req.baseUrl and req.path and both are undefined.
Your Node.js server always returns a HTML file and sets the content type to HTML, so when your website requests the JavaScript file, it returns a HTML file, causing the Uncaught SyntaxError: Unexpected token '<' error. To fix the error, don't set the content type and let the browser figure it out, and also modify the code to return the requested file.
I have written some possible code below. However, it will need to be modified to suit your file structure.
const server = http.createServer((req, res) => {
console.log("request received");
console.log(req.headers.referer);
fs.readFile('./' + req.url, function (error, data) {
res.end(data);
});
});

Syntax error with NodeJS and HTTP

var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.writeHead(" This is just a start.. Remember what u thought of it.");
reponse.end();
}).listen(8888);
This is my JS code in a file named server.js which I wanted to execute through Node.js, but it's giving an error:
SyntaxError: Unexpected identifier
The path of the file, server.js is in D Drive, same as where I installed Node.js. What should I do ?
Use this code:
var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(" This is just a start.. Remember what u thought of it.");
response.end();
}).listen(8888);
Save it in a file named "server.js" and run it with:
node server.js
I don't know if it's a typo in your question but you use reponse instead of response:
var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.writeHead(" This is just a start.. Remember what u thought of it.");
reponse.end(); // <------
}).listen(8888);

node.js Error: connect ECONNREFUSED; response from server

I have a problem with this little program:
var http = require("http");
var request = http.request({
hostname: "localhost",
port: 8000,
path: "/",
method: "GET"
}, function(response) {
var statusCode = response.statusCode;
var headers = response.headers;
var statusLine = "HTTP/" + response.httpVersion + " " +statusCode + " " + http.STATUS_CODES[statusCode];
console.log(statusLine);
for (header in headers) {
console.log(header + ": " + headers[header]);
}
console.log();
response.setEncoding("utf8");
response.on("data", function(data) {
process.stdout.write(data);
});
response.on("end", function() {
console.log();
});
});
The result in console is this:
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
I do not understand why this happens.
From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).
The problem might be you have not created server on your local machine which listens to port 8000.
For that you have to set up server on localhost which can serve your request.
Create server.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Run server.js : node server.js
Run file that contains code to make request.
Please use [::1] instead of localhost, and make sure that the port is correct, and put the port inside the link.
const request = require('request');
let json = {
"id": id,
"filename": filename
};
let options = {
uri: "http://[::1]:8000" + constants.PATH_TO_API,
// port:443,
method: 'POST',
json: json
};
request(options, function (error, response, body) {
if (error) {
console.error("httpRequests : error " + error);
}
if (response) {
let statusCode = response.status_code;
if (callback) {
callback(body);
}
}
});
I solved this problem with redis-server, you can install that like this!
sudo apt-get install redis-server
after that see the port and change it!
I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...
Just run the following command in the node project:
npm install
Its worked for me.
i ran the local mysql database, but not in administrator mode, which threw this error
If you have stopped the mongod.exe service from the task manager, you need to restart the service. In my case I stopped the service from task manager and on restart it doesn't automatically started.
I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.
If this is the problem with connecting to the redis server (if your redis.createClient function does not work although you are sure that you have written the right parameters to the related function), just simply type redis-server in another terminal screen. This probably gonna fix the issue.
P.S.: Sorry if this is a duplicate answer but there is no accepted answer, so, I wanted to share my solution too.
This is very slight error. When I was implementing Event server between my processes on nodejs.
Just check for the package you're using to run your server like Axios.
Maybe you might have relocated the files or disconnected some cache data on the browsers.
It's simple ,In your relevant directory run the following command
I was using axios so I used
npm i axios
Restart the server
npm start
This will work.
use a proxy property in your code it should work just fine
const https = require('https');
const request = require('request');
request({
'url':'https://teamtreehouse.com/chalkers.json',
'proxy':'http://xx.xxx.xxx.xx'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = body;
console.log(data);
}
}
);

Running Node.js Server using User Level Root

Basic question but not sure where to turn to start figuring this out.
I've setup a very simple node server on port 3000 that just responds with an index.html file. When I call http://localhost:3000 in the browser, I get the proper page served up with dependencies. I don't want to authenticate every time though so I'd like to run it from the user-level.
I tried typing http://localhost~myusername:3000 in the browser but I keep getting:
The requested URL /~myusername:3000 was not found on this server.
(I have setup user-level root to be accessed through ~/Sites and have gotten access to files through here, even php, it's just when I start using a node server this problem occurs.)
How can I get node.js to respond to user-level requests? And it serve up the proper index.html from the relative path of the user-level root instead of /library/WebServer/Documents?
Update
Code of server.js:
var http = require('http');
var fs = require('fs');
function send404(response) {
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.write('Error 404: Resource not found.');
response.end();
}
var server = http.createServer(function (req, res) {
if (req.method == 'GET' && req.url == '/') {
res.writeHead(200, { 'content-type': 'text/html' });
fs.createReadStream('./index.html').pipe(res);
}
else {
send404(res);
}
}).listen(3000);
console.log('server running on port 3000');

Executing javascript code with node.js

I'm trying to execute a javascript code with node.js, and I get always two errors saying :
.port 1 is not active
.port 2 is not active
This my javascript code :
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
Any ideas ?
Do you have anything else listening on 8124 already?
netstat -an|grep :8124

Categories