Node.js HTTP服务器路由

2ul0zpep  于 2023-08-04  发布在  Node.js
关注(0)|答案(4)|浏览(114)

下面的node.js代码是使用express来路由到不同的url,我如何用http代替express来做同样的事情?

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!');
});

字符串

wdebmtf2

wdebmtf21#

这里有一个简单的例子。显然,有很多方法可以做到这一点,这可能不是最可扩展和最有效的方法,但它希望能给予你一个想法。

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!');
});

字符串

r1zhe5dt

r1zhe5dt2#

验证码:这是一个很基本的例子

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
});

字符串

shyt4zoc

shyt4zoc3#

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支持。

wxclj1h5

wxclj1h54#

您将使用由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
  }
}

字符串

相关问题