Node.js HTTP服务器路由

13

以下 Node.js 代码使用 Express 来路由到不同的 URL,如何在没有 Express 的情况下使用 HTTP 实现相同的功能?

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

app.use(express.static('public'));

app.get('/', function (req, res) {
    res.send('Welcome Home');
});

app.get('/tcs', function (req, res) {
    res.send('HI RCSer');
});


// Handle 404 - Keep this as a last route
app.use(function(req, res, next) {
    res.status(404);
    res.send('404: File Not Found');
});

app.listen(8080, function () {
    console.log('Example app listening on port 8080!');
});
4个回答

16

尝试下面的代码。 这是一个相当基本的示例

var http = require('http');

//create a server object:

http.createServer(function (req, res) {
 res.writeHead(200, {'Content-Type': 'text/html'}); // http header
var url = req.url;
 if(url ==='/about'){
    res.write('<h1>about us page<h1>'); //write a response
    res.end(); //end the response
 }else if(url ==='/contact'){
    res.write('<h1>contact us page<h1>'); //write a response
    res.end(); //end the response
 }else{
    res.write('<h1>Hello World!<h1>'); //write a response
    res.end(); //end the response
 }
}).listen(3000, function(){
 console.log("server start at port 3000"); //the server object listens on port 3000
});

15

这里有一个快速的例子。显然,有很多方法可以做到这一点,而且这可能不是最可扩展和高效的方式,但它希望能够给您一个想法。

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {

    req.on('error', err => {
        console.error(err);
        // Handle error...
        res.statusCode = 400;
        res.end('400: Bad Request');
        return;
    });

    res.on('error', err => {
        console.error(err);
        // Handle error...
    });

    fs.readFile('./public' + req.url, (err, data) => {
        if (err) {
            if (req.url === '/' && req.method === 'GET') {
                res.end('Welcome Home');
            } else if (req.url === '/tcs' && req.method === 'GET') {
                res.end('HI RCSer');
            } else {
                res.statusCode = 404;
                res.end('404: File Not Found');
            }
        } else {
            // NOTE: The file name could be parsed to determine the
            // appropriate data type to return. This is just a quick
            // example.
            res.setHeader('Content-Type', 'application/octet-stream');
            res.end(data);
        }
    });

});

server.listen(8080, () => {
    console.log('Example app listening on port 8080!');
});

0

express也可以直接被http使用。 来源:https://expressjs.com/en/4x/api.html#app.listen

通过express()返回的应用实际上是一个JavaScript函数,旨在作为回调传递给Node的HTTP服务器以处理请求。

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

http.createServer(app).listen(80)

通过这样做,你仍然可以利用express进行路由,同时保持本地http支持。


0
你将使用由http.Server创建的IncomingMessage对象的.url作为路径匹配的基础。你希望使用.startsWith而不是等号运算符(===),以支持查询参数。例如:
const SERVER = http.createServer(async function(request, response) {
  if (request.url.startsWith('/store')){
    // handle /store?product=shoe&brand=nike&color=blue
  } else if (request.url.startsWith('/auth')){
    // handle /auth?jwt
  } else {
    // handle index or / path
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接