I just installed node and tried to write and run some programs.
When I tried this example progra, I get an error.
Maybe node and npm were installed incorrectly?
Maybe some necessary packages should be install?
const http = require('http');
const net = require('net');
const url = require('url');
// Create an HTTP tunneling proxy
var proxy = http.createServer( (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
proxy.on('connect', (req, cltSocket, head) => {
// connect to an origin server
var srvUrl = url.parse(`http://${req.url}`);
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n');
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
});
});
Why does the below error appear?
var proxy = http.createServer( (req, res) => {
^
SyntaxError: Unexpected token >
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3 ##
Try it like this;
var requestListener = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
}
var proxy = http.createServer(requestListener);
Related
Im trying to create a http server using node.js.
This works for me:
const http = require('http');
const server = http.createServer((req, res) => {
console.log(req.url);
res.end('Hello Node.js');
});
server.listen(3000);***
But this throws an error:
const http = require('http');
function onRequest(req, res) {
console.log(req.url);
res.end('Hello World');
};
const server = http.createServer(onRequest(res, res));
server.listen(3000);
I get the following error:
code
ReferenceError: req is not defined
at Object.<anonymous> (C:\Users\NAME\Desktop\socket-first-project\index.js:3:34)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
It should be the same, right?
createServer expects you to pass it a function.
You are immediately calling onRequest and passing its return value … or would be if you had defined res which you are trying to pass to it as an argument (twice!).
const server = http.createServer(onRequest);
Compare:
function myFunction(anArgument) {
return anArgument;
}
const argument = 1;
console.log(typeof myFunction);
console.log(typeof myFunction(argument));
On the second to last line you have added res twice instead of (req, res). Try replacing the first res with req.
I am creating an API, so I want to add a user system and validate access to the API.
This would be the middleware for validation:
'use strict'
const jwt = require('jwt-simple');
const moment = require('moment');
const config = require('../settings/config');
function isAuth(req, res, next) {
if (!req.headers.authotization) {
return res.status(403).send({
message: `No tiene autorizacion`
})
}
const token = req.headers.authotization.split(" ")[1];
const payload = jwt.decode(token, user, config.token.secret_token);
if (payload.exp <= moment().unix()) {
return res.status(401).send({
message: 'El token ha expirado'
})
req.user = payload.sub;
next();
}
}
module.exports = isAuth;
while this would be the route:
'use strict'
const express = require('express');
const router = express.Router();
const auth = require('../middlewares/auth');
router.get('/', auth.isAuth, (req, res) => {
res.status(200).send({
message: `Tienes acceso`
})
})
on the other hand, this is my main application settings (app.js):
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const config = require('./config')
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
// Routes variables
const productRouter = require('../routes/product');
const privateRouter = require('../routes/private');
// Routes uses
app.use('/api/product', productRouter);
app.use('/private', privateRouter);
app.listen(config.app.port, err => {
if (err) throw err;
console.log(`Server listening on port ${config.app.port}`)
})
module.exports = app;
I am getting this error:
D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object
Undefined]
at Route. [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202:15)
at Function.proto. [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:510:19)
at Object. (D:\api-rest-carlos-azaustre\routes\private.js:6:8)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (D:\api-rest-carlos-azaustre\settings\app.js:15:23)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18) [nodemon] app crashed - waiting for file changes before starting...
And sometimes this line is added at the top of error:
(node:3092) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners > added to [Bus]. Use emitter.setMaxListeners() to increase limit
After reading the answers, I edit my question. I have placed only auth and not auth.isAuth and I am getting the following error:
D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a
Object
at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:458:13)
at Function. (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:220:21)
at Array.forEach ()
at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:217:7)
at Object. (D:\api-rest-carlos-azaustre\settings\app.js:20:5)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (D:\api-rest-carlos-azaustre\index.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14) [nodemon] app crashed - waiting for file changes before starting...
Does anybody know what is it due to?
module.exports = isAuth; means you're only exporting the function and nothing else. That means when you do const auth = require('../middlewares/auth');, auth is the actual function, not an object containing isAuth as a property.
So, doing router.get('/', auth, (req, res) => { should work, instead of auth.isAuth which is invalid.
Learn more about modules here: https://js.evie.dev/modules
Yes, you export the function with this code: module.exports = isAuth;
But then you call use it like this: auth.isAuth
Assuming you're doing something like const auth = require('./bin/auth.js'); or whatever
auth would be the function itself -- there will be no isAuth property.
So you should try this:
router.get('/', auth, (req, res) => {
You haven't posted your entire code, so this is just a best guess.
Im trying to run this simple code but I m getting error all the time...I really dont know what's the problem. It seems to me very Ok...? Thanks!
var http = require(http);
console.log('Starting');
var host = '127.0.0.1';
var port = 1337;
var server = http.createServer(function(request, response){
console.log('Receive request: '+ request.url);
response.writeHead(200, {"Content-type" : "text/plain"});
response.end("Hello world");
});
server.listen(port, host, function(){
console.log('Listening: ' + host + ':' + port);
});
Console error is this:
assert.js:98
throw new assert.AssertionError({
^
AssertionError: path must be a string: path must be a string
at Module.require (module.js:362:3)
at require (module.js:380:17)
at Object.<anonymous> (/Users/yoniPacheko/PhpstormProjects/angularJS/nodeJS/server.js:9:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
In your first line there are quotes missing around http:
var http = require('http');
In my case, I had
var http = require('http');
var path= require('path');
As soon as I deleted the the http line, it worked for me.So, i did leave only
var path= require('path');
I was working on express,mongodb,socket.io.
This is my server.js code
var express = require('express');
feeds = require('./routes/whatshappeningfeed');
var http = require('http');
var pathname = require('path');
// Test services - to be removed
courses = require('./routes/courses');
auth = require('./routes/auth');
token = require('./routes/token');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
});
app.use(function (error, req, res, next) {
if (!error) {
next();
} else {
console.error(error.stack);
res.send(500);
}
});
app.get('/me/whatshappeningfeed',feeds.getfeeds);
app.get('/courses', courses.findAll);
app.get('/courses/:id', courses.findById);
app.get('/token', token.auth);
app.get('/auth', auth.auth);
app.get('/refresh', auth.refresh);
app.listen(80);
console.log('Listening on port 80...');
this is my error message :
F:\NODE.JS\poc\node_modules\express\lib\router\index.js:291
throw new Error(msg);
^
Error: .get() requires callback functions but got a [object Undefined]
at F:\NODE.JS\poc\node_modules\express\lib\router\index.js:291:11
at Array.forEach (native)
at Router.route (F:\NODE.JS\poc\node_modules\express\lib\router\index.js:287:13)
at Router.(anonymous function) [as get] (F:\NODE.JS\poc\node_modules\express\lib\router\index.js:318:16)
at Function.app.(anonymous function) [as get] (F:\NODE.JS\poc\node_modules\express\lib\application.js:431:26)
at Object.<anonymous> (F:\NODE.JS\poc\server.js:44:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
When i run the node server.js file i got above error. it was working earlier. i couldn't sort out the issue. please anyone help me.
The error says it all, app.get() requires a callback function. So it means that one or more of your routes are missing a callback.
ALL of your routes should have a function(req,res), whether explicitely as in the example or in another function (see comments) :
app.get('/me/whatshappeningfeed', function(req,res){ //request, response
//then here you can define what your server should send as a response when queries for /me/whatshappeningfeed
res.send(feeds.getfeeds()); //this will send back to the browser the result of feeds.getfeeds()
});
Also, not sure if it's due to the copypaste you did, but the first semicolon require('express'); should be a comma.
I am working to load JSON data using Node/express.js and plot it on map. As first start, I am inspired by the example presented in the repp leaflet-geojson-stream. https://github.com/tmcw/leaflet-geojson-stream/tree/master/example
Client:
https://github.com/tmcw/leaflet-geojson-stream/blob/master/example/client.js
var L = require('leaflet'),
leafletStream = require('../');
L.Icon.Default.imagePath = 'http://leafletjs.com/dist/images';
window.onload = function() {
var div = document.body.appendChild(document.createElement('div'));
div.style.cssText = 'height:500px;';
var map = L.map(div).setView([0, 0], 2);
L.tileLayer('http://a.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var gj = L.geoJson().addTo(map);
leafletStream.ajax('/points.geojson', gj)
.on('end', function() {
});
};
Server :
https://github.com/tmcw/leaflet-geojson-stream/blob/master/example/server.js
var express = require('express'),
browserify = require('browserify'),
app = express();
app.get('/', function(req, res) {
res.send('<html><head><link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" /></head><body><script src="bundle.js"></script></html>');
});
app.get('/bundle.js', function(req, res) {
var b = browserify();
b.add('./client.js');
b.bundle().pipe(res);
});
app.get('/points.geojson', function(req, res) {
res.write('{"type":"FeatureCollection","features":[');
var i = 0, die = 0;
function send() {
if (++i > 20) {
res.write(JSON.stringify(randomFeature()) + '\n,\n');
i = 0;
} else {
// it seems like writing newlines here causes the buffer to
// flush
res.write('\n');
}
if (die++ > 1000) {
res.write(JSON.stringify(randomFeature()));
res.write(']');
res.end();
return;
}
setTimeout(send, 10);
}
send();
});
app.listen(3000);
function randomFeature() {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [
(Math.random() - 0.5) * 360,
(Math.random() - 0.5) * 180
]
},
properties: {}
};
}
In the project, they create random json file. I wanted to read json file, then plot it. The reason I want to "Stream data" is to deal with the size of file (I know that there is better and easier ways to load json data), But I wanted to use this module.
I modified the server script :
var express = require('express'),
browserify = require('browserify'),
app = express();
app.get('/', function(req, res) {
res.send('<html><head><link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" /></head><body><script src="bundle.js"></script></html>');
});
app.get('/bundle.js', function(req, res) {
var b = browserify();
b.add('./client.js');
b.bundle().pipe(res);
});
var o = require('../output_.geojson');
app.get('/points.geojson', function(req, res) {
res.json(o);
});
app.listen(3000);
res.write('');
But I am getting error :
/Users/macbook/leaflet-geojson-stream/output_.geojson:1
(function (exports, require, module, __filename, __dirname) { "type":"FeatureC
^
SyntaxError: Unexpected token :
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/macbook/leaflet-geojson-stream/example/server.js:15:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
Can anyone give a hint on what should I do in order to read and load json external file to plot the data.
The : isn't expected, because you're in a function at that point.
To parse JSON, you simply have to call JSON.parse(), as stated in How to parse JSON using Node.js?. So you read the file, get the JSON String that's in there, and put it through JSON.parse()
You are currently loading the whole JSON file into memory by 'requiring' it.
Instead you want to stream the file because it is big and so use the fs.createReadStream function:
var fs = require('fs');
app.get('/points.geojson', function(req, res) {
res.setHeader('Content-Type', 'application/json');
fs.createReadStream(__dirname + '../output_.geojson').pipe(res);
});
Also make sure that the contents of ../output_.geojson is actually valid JSON. You can use JSONLint to check - the file should with '{' or '[' and NOT have Javascript functions inside.