简体   繁体   English

使用Express设置基本服务器

[英]Using express to set up a basic server

I have a node.js application and I am stuck getting an error message when I try to load the homepage. 我有一个node.js应用程序,尝试加载主页时遇到错误消息。 I will do my best at laying out my architecture below. 我将尽力在下面布置我的体系结构。 It goes index.js --> server.js --> router.js --> requestHandlers.js 它去了index.js-> server.js-> router.js-> requestHandlers.js

I am using a combination of express (www.expressjs.com) and nodebeginner.org. 我正在使用express(www.expressjs.com)和nodebeginner.org的组合。 Sorry for the long question.. just wanted to get as much information down as possible. 很抱歉,这个问题很久..只是想获取尽可能多的信息。

index.js (creates handle object that contains pathname/requesthandler information, calls function to start server) I start with router.route here and pass it along each step index.js(创建包含路径名/请求处理程序信息的句柄对象,调用函数以启动服务器)我从router.route开始,并沿每个步骤传递

var server = require("./server");
var router = require('./router');
var requestHandlers = require('./requestHandlers');

// Routes

var handle = {}
handle['/'] = requestHandlers.home;

server.start(router.route, handle)

server.js (starts the server, THIS IS WHERE I WANT TO CONFIGURE THE SERVER, gets a the pathname from the URL, and passes it on to the route module) server.js(启动服务器,这是我要配置服务器的位置,从URL获取路径名,并将其传递给路由模块)

var http = require("http");
var url = require('url');
var express = require('express');

function start (route, handle) {
    var onRequest = function(request, res) {
        var pathname = url.parse(request.url).pathname;
        console.log("request for " + pathname + " recieved.");
        route(handle, pathname, res);
    }

    var app = express.createServer(onRequest).listen(8888);
    if (app.configure) {
        console.log('app exists'); //logging correctly
    }
    // Configuration
     app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

    console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); //logs correct with 8888 and development
}

exports.start = start;

router.js (the function route passed from index --> server which calls the route function in router.js, calls the requestHandler that matches the pathname in handle object) router.js(从索引->服务器传递的函数路由,该函数调用router.js中的route函数,并调用与句柄对象中的路径名匹配的requestHandler)

function route (handle, pathname, res) {

    console.log("About to route a request for" + pathname); //About to route a request for/stylesheets/style.css SEE BELOW******* this is the error

if (typeof handle[pathname] === 'function') {
        handle[pathname] (res);
    }
    else {
        console.log('no request handler found for' + pathname);
    }
}

exports.route = route;

requestHandler.js (interacts with the res/req objects, functions are mapped to certain pathnames, only called when those pathnames are requested thanks to the router) requestHandler.js(与res / req对象进行交互,将功能映射到某些路径名,只有在通过路由器请求了这些路径名时才调用它们)

var home = function(res){
  res.render('index', { title: 'WWYB?' });
  console.log('homepage rendered'); //correctly logs for pathname = '/'
  //click();
};

exports.home = home;

** *when i go to request localhost:8888 it tries to make a bunch of requests. ** *当我去请求localhost:8888时,它尝试发出一堆请求。 first it requests "/" correctly but then keeps going through logging everything saying "About to route a request for/stylesheets/style.css" Eventually the page loads with no css. 首先它正确地请求“ /”,然后继续记录所有内容,说“关于为/stylesheets/style.css路由请求”,最终页面加载时没有CSS。 The pathname as indicated in my layout.jade file is exactly that '/stylesheets/style.css'. 我的layout.jade文件中指示的路径名恰好是“ /stylesheets/style.css”。

Why is the pathname ever evaluating to /stylesheets/style.css? 为什么路径名曾经评估为/stylesheets/style.css? I think node is doing something in the background and I dont fully understand it. 我认为节点在后台执行某项操作,但我并不完全了解。

Let me know if you need more info. 让我知道您是否需要更多信息。 Thanks! 谢谢!

Like @TJHolowaychuk commented you really should check the manual, and follow a bunch of tutorials. 就像@TJHolowaychuk所说,您确实应该检查手册,并遵循大量教程。 Anyway, I'll try to help you a bit. 无论如何,我会尽力帮助您。

The is a very basic explanation. 这是一个非常基本的解释。 Express allows you to use sub applications, so you can have different part of you application in different files. Express允许您使用子应用程序,因此您可以在不同文件中拥有应用程序的不同部分。 It has it's own router too. 它也有自己的路由器。 If you need to do something with the request and/or the response before the route is processed, you can create a middleware. 如果您需要在处理路由之前对请求和/或响应进行某些操作,则可以创建一个中间件。 If you want you configurations in a different module, then return a function in it. 如果要在其他模块中进行配置,请在其中返回一个功能。

So an example of server.js : 因此有一个server.js的示例:

var  $express = require('express'),
          app = module.exports = $express.createServer(),
       subapp = require('./subapp'),
    configure = require('./configure');

// Each of our own configure returns a function that will be
// called by app.configure
app.configure(configure.all(app));
app.configure('development', configure.devel(app));
app.configure('production', configure.prod(app));

// Use our sub application
app.use(subapp);

// Now listen
app.listen(3030)

subapp.js : subapp.js:

var $express = require('express'),
    subapp = module.exports = $express.createServer();

// Add a handler for GET / to our sub-application
subapp.get('/', function (req, res) {
   res.end('Hello world!');
});

Finally configure.js : 最后configure.js:

var $express = require('express');

exports.all = function (app) {
   return function () {
      // Global configurations

      app.use($express.bodyParser());
      app.use($express.methodOverride());
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
      app.use($express.static(__dirname + '/public'));
      //...

      // If you want to do something with/on the request/response
      // you can create a middleware
      app.use(function (req, res, next) {
         console.log('caught request %s %s', req.method, req.path);

         // Don't forget the callback
         next();
      });
   };
};

exports.devel = function (app) {
   return function () {
      // Development configurations
   };
};

//...

Go to localhost:3030 with your favorite browser, it displays "Hello world!", this is our request handler. 使用您喜欢的浏览器转到localhost:3030 ,它显示“ Hello world!”,这是我们的请求处理程序。 If you look at the terminal, you'll see "caught request GET /", this is our middleware. 如果您查看终端,则会看到“捕获的请求GET /”,这是我们的中间件。

Your stylesheets, client-side javascripts, etc. should be in /public. 您的样式表,客户端JavaScript等应位于/ public中。 app.use(express.static(__dirname + '/public')) will serve these. app.use(express.static(__dirname + '/public'))将为您服务。

Let's say you have /public/stylesheets/all.css , then in your jade template you can include it like this link(rel='stylesheet', href='/public/stylesheets/all.css') 假设您拥有/public/stylesheets/all.css ,那么在您的Jade模板中,您可以像以下link(rel='stylesheet', href='/public/stylesheets/all.css')一样包含它link(rel='stylesheet', href='/public/stylesheets/all.css')

Now, you'll have to experiment and learn more about node and express before even thinking to deploy something to production, these websites may help you: 现在,您甚至必须考虑将某些东西部署到生产环境之前,都必须试验并学习有关节点和表达的更多信息,这些网站可能会帮助您:

Hope this tiny-micro-tut helps you. 希望这个微小的tut帮助您。

哇,这很令人困惑,您可能想从Express(1)可以为您生成的应用程序开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM