The below code is from server.js, it's causing my server to crash with Error:
ReferenceError: server is not defined at Object. (C:\xampp\htdocs\api\src\server.js:17:18) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10) at run (bootstrap_node.js:418:7) at startup (bootstrap_node.js:139:9) at bootstrap_node.js:533:3
var express = require('express');
var body_parser = require('body-parser');
var app = express()
// Port config
var port = 3000;
app.use(body_parser.json());
// Use prefix of api
app.use('/api', require('../routes/api.js')(express));
app.listen(port, function(){
console.log('Server Active on', port);
});
module.exports = server;
Mocha testing (__app.js)
var request = require('supertest');
describe('API', function() {
var server;
beforeEach(function () {
server = require('../src/server.js');
});
afterEach(function () {
server.close();
});
it('/ should return specified object.', function (done) {
request(server)
.get('/api/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {"hello": "world"}, done);
});
it('/status should return specified healthy:true', function (done) {
request(server)
.get('/api/status')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {"healthy": true}, done);
});
it('/user/id should return user object with id.', function (done) {
var fakeUserID = 374;
request(server)
.get('/api/user/347' + fakeUserID)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {user: {id: fakeUserID}}, done);
});
});
Am I missing a package? I'm watching a video with the same exact code and it doesn't crash the server.
You want to export the app. No variable called server exists
module.exports = app;
You can then import the app elsewhere in your project using require
server is not defined anywhere. As a guess, you probably want to change the last line to:
module.exports = app;
You should try this:
const server = app.listen(port, function(){
console.log('Server Active on', port);
});
Related
enter image description here
here's the app.js(--please find attached image):
//here's the app.js
const express = require("express");
const app = express();
app.use(express.json());
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
const authJwt = require("./helpers/jwt");
const errorHandler = require("./helpers/error-handler");
app.use(cors());
app.options('*', cors());
//middleware
app.use(morgan("tiny"));
app.use(authJwt());
app.use(errorHandler()); //-> **this isn't correct?**
//Importing routing of products
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const req = require("express/lib/request");
const res = require("express/lib/response");
const api = process.env.API_URL;
//routers
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/orders`, ordersRoutes);
app.use(`${api}/users`, usersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewurlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("database connection is ready");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("Server is Running http://http://localhost:3000");
});
//error image
//here's the error handler code
function errorHandler(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
}
module.exports = errorHandler;
> Blockquote (--please find attached image)
here's the error
C:\Users\steve\Backend\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\steve\Backend\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\steve\Backend\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
Your error handler function is correct, but the problem is that you're calling the function instead of passing it directly to your express app.
Remove the parenthesis after the errorHandler and it should work.
app.use(errorHandler); // Don't call errorHandler, express will call it
Think of it like this.
if I just call errorHandler() in any context it won't return anything.
That means that errorHandler() evaluates to undefined.
Now in your code, when you do app.use(errorHandler()) instead of evaluating to the following:
app.use(function(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
});
Your code is actually evaluating to
app.use(undefined);
and so express is throwing an error because undefined is not a function.
I am a total noob in Backend and I am learning Express and using HBS as template engine.
This happens to me every time while using hbs partials in Express.
Code
const express = require("express");
const app = express();
const hbs = require("hbs");
const path = require("path");
const port = process.env.PORT || 3000;
// public static path
const static_path = path.join(__dirname, "../public");
const templates_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
app.set("view engine", "hbs");
app.set("views", templates_path);
hbs.registerPartial(partials_path);
app.use(express.static(static_path));
// routing
app.get("/", (req, res) => {
res.render("index");
});
app.get("/about", (req, res) => {
res.render("about");
});
app.get("/weather", (req, res) => {
res.render("weather");
});
app.get("*", (req, res) => {
res.status(404).render("404error");
});
app.listen(port, () => {
console.log("listning on port " + port);
});
Error
throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
^
Error: Attempting to register a partial called "D:\Projects\ExpressWeb\templates\partials" as undefined
at HandlebarsEnvironment.registerPartial (D:\Projects\ExpressWeb\node_modules\handlebars\dist\cjs\handlebars\base.js:80:15)
at Instance.registerPartial (D:\Projects\ExpressWeb\node_modules\hbs\lib\hbs.js:222:35)
at Object.<anonymous> (D:\Projects\ExpressWeb\src\app.js:15:5)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47 {
description: undefined,
fileName: undefined,
lineNumber: undefined,
endLineNumber: undefined,
number: undefined
}
Adding this to increase the discripting because Stack Overflow is not letting me post this because i am uplaoding more code than discription and i dont know what to ask more.
According to the docs it is - hbs.registerPartials(partials_path);
not hbs.registerPartial(partials_path);
I want to make an OCR program but I fund some problems during the declaration of 'Tesseract.recognize' method
here is my code :
const express = require('express');
const fs= require('fs');
const multer = require('multer');
const Tesseract = require('Tesseract.js');
const app = express();
// app.use(bodyParser.urlencoded({extended: true}))
const PORT = process.env.PORT | 5000;
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'images')
},
filename: function (req, file, callback) {
callback(null, file.orignalname);
}
});
var upload = multer({
storage: Storage
}).array('image', 3);
//route
app.post('/', (req, res) => {});
app.post('/upload', (req, res) => {
console.log(req.file);
upload(req, res , err => {
if (err) {
console.log(err);
return res.send('somthing went wrong');
}
return res.send('file uploaded successfully');
});
});
var image = fs.readFileSync(__dirname + '/images/cv.jpg',
{
encoding:null
});
Tesseract.recognize(image)
.progress(function(p) {
console.log('progress', p);
})
.then(function(result) {
res.send('result', result);
});
app.listen(PORT, () => {
console.log('Server running on PORT ${PORT}')
});
and this is my terminal result:
.progress(function(p) {
^
TypeError: Tesseract.recognize(...).progress is not a function
at Object.<anonymous> (C:\Users\de\Desktop\MR.Azmani Project\ANGULAR\ocr\server.js:46:6)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
[nodemon] app crashed - waiting for file changes before starting...
and this it what is the result how should look like in the treminal during the process
and this is the final result in the termilal
thank you
.progress was removed in version 2 of tesseract.js (there's a blog post about that here. Version one is still on Github here, and probably still works, so you can npm i tesseract.js#1.0.19 to get the behavior you're expecting, or see the docs and examples for the current version to get your code updated for v2.
So it's the first ever program I write but when I run it in the console I get this error.
module.js:540
throw err;
^
Error: Cannot find module 'C:\Users\Daniel\Desktop\app'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have no idea why this is happening as I am new but I checked the code and nothing is wrong.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-type', 'text/plain');
res.end('Hello World!');
});
server.listen(port, hostname, () => {
console.log('Server started on port '+port);
});
It seems like the script you wanted to execute isn't named "app".
Check the Path and name of your script when you execute it with the node command.
I was starting to learn NodeJS and when I implemented the first script, I get the following error:
http.listen(3000,() => console.log('Server running on port 3000'));
^
TypeError: http.listen is not a function
at Object.<anonymous> (C:\Users\I322764\Documents\Node\HelloNode.js:11:6)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3
The corresponding script is as follows:
'use strict';
const http = require('http');
http.createServer(
(req, res) => {
res.writeHead(200, {'Content-type':'text/html'});
res.end('<h1>Hello NodeJS</h1>');
}
);
http.listen(3000,() => console.log('Server running on port 3000'));
The version of node is 4.2.4
When you write:-
http.createServer(function(req,res){
res.writeHead(200);
res.end("Hello world");
});
http.listen(3000);
http.createServer() returns an object called Server. That Server object has listen method available. And you are trying to access that listen method from the http itself. That's why it shows that error.
so you can write it like:-
var server=http.createServer(function(req,res){
res.writeHead(200);
res.end("Hello world");
});
server.listen(3000,function(){
console.log('Server running on port 3000')
});
Now it will let your server listen on the port 3000.
listen isn't a function of http, but a method of the server you create with createServer:
var server = http.createServer((req, res) => {
res.writeHead(200, {'Content-type':'text/html'});
res.end('<h1>Hello NodeJS</h1>');
});
server.listen(3000,() => console.log('Server running on port 3000'));