I'm trying to create a simple express application but it seems not to be working

时间:2017-12-18 06:27:37

标签: javascript node.js express

I'm trying to create a simple express application but while it is running in console. when i hit localhost:3000 in my browser I get network errors. I don't seem to know what the problem is.

Here is my code.

 var hostname = 'localhost';
 var port = 3000;

 var app = express ();

 app.use (function (req, res, next) {
     console.log (req.headers);

     res.writeHead (200, {'Content-Type': 'text/html'});
     res.end ( '<html><body><h1>Hello world</h1></body></html>');
 });


 // listing for request at port: 7000 no http.createServer needed

 app.listen (console.log (
  `Success server running at http://${hostname}: ${port}`
 ));

However when I created a similar app in pure node it worked fine.

Here is my code:

 var fs = require('fs');
 var path = require ('path');
 var http = require ('http');

 var hostname = 'localhost';
 var port = 3000;

 var server = http.createServer (function (req, res) {
   console.log ('request for ' + req.url + ' using ' + req.method + ' method');


    // checking if the request method is Get
    if (req.method == 'GET') {

        var fileUrl;
        // checking for the request url if it is the home page or not and storing the correct request url in fileUrl variable
            if (req.url == '/') fileUrl = '/index.html';
                 else fileUrl = req.url;
            var filePath = path.resolve ('./public'+fileUrl);
            var fileExt = path.extname (filePath);

            if (fileExt == '.html' && req.url !== '/favicon.ico') {
                fs.exists (filePath, function (exists) {
                   if (!exists) {
                    res.writeHead (404, {'content-type': 'text/html'});
                    res.end ('<h1> The file </h1>' + fileUrl + '<h1>is not found. Make sure your browser input is correct and try again!</h1>');
                    console.log('hello no favicon found');
                    return;
                   }
                });
            }

        res.writeHead (200, {'content-type': 'text/html'});
        fs.createReadStream (filePath).pipe(res);  
    } else {
        res.writeHead (404, {'content-type': 'text/html'});
        res.end ('<h1> The file' + fileUrl + 'not an html file');
        console.log (fileUrl);
    }
 });


 server.listen (port, hostname, function (){
     console.log (`server started ${hostname}:${port}. Helloooooo`);
 });

Thanks for your review and response!

3 个答案:

答案 0 :(得分:1)

There are couple of issues in your code.

You should install express in your project. You can use the below command to do so.

npm install express --save

And then use the below code on top.

var express = require('express');
var app = express();

Then, you must provide a port parameter in the listen call.

app.listen(3000);

Other APIs and options can be found here.

答案 1 :(得分:0)

you are missing the line.

var express = require('express')

add this line on the top of your code and try and don't forget to add NPM module express

答案 2 :(得分:0)

I recommend you to use the app generator from express, fast and easy, you'll get the basic working structure.

http://expressjs.com/en/starter/generator.html

Express application generator Use the application generator tool, express-generator, to quickly create an application skeleton. The express-generator package installs the express command-line tool. Use the following command to do so:

height: 100%;

Display the command options with the -h option:

$ npm install express-generator -g

For example, the following creates an Express app named myapp. The app will be created in a folder named myapp in the current working directory and the view engine will be set to Pug:

   $ express -h

Usage: express [options] [dir]
Options:
-h, --help          output usage information
        --version       output the version number
    -e, --ejs           add ejs engine support
        --hbs           add handlebars engine support
        --pug           add pug engine support
    -H, --hogan         add hogan.js engine support
    -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
    -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory

Then install dependencies:

$ express --view=pug myapp

create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.css
   create : myapp/views
   create : myapp/views/index.pug
   create : myapp/views/layout.pug
   create : myapp/views/error.pug
   create : myapp/bin
   create : myapp/bin/www

On MacOS or Linux, run the app with this command:

$ cd myapp
$ npm install

On Windows, use this command:

$ DEBUG=myapp:* npm start

Then load http://localhost:3000/ in your browser to access the app. The generated app has the following directory structure:

> set DEBUG=myapp:* & npm start