首页 > 解决方案 > 将任何路由到单个端点并将特定路由到另一个端点?

问题描述

我想将所有请求路由到一个特定的端点,除了一个,它将转到另一个端点。例如:

//I cannot use express
const http = require('http');
const url = require('url');

http.createServer((req, res) => {
    const reqUrl = url.parse(req.url, true);
    if (reqUrl.pathname == '*' && req.method === 'GET') { //route all to this one
        // process
        res.end();
    }
    if (reqUrl.pathname == '/specific' && req.method === 'GET') { //unless the user types in /specific
        //process
        res.end();
    }
}).listen(port, hostname, () => {
    console.log(`Server running on port ${port}`);
});

我怎样才能做到这一点?

标签: node.js

解决方案


先放你的具体路线,然后放你的一般路线:

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

http.createServer((req, res) => {
  const reqUrl = url.parse(req.url, true);
  if (reqUrl.pathname == '/specific' && req.method === 'GET') { //unless the user types in /specific
    //process
    res.end();
  }
  else { //route all to this one
    // process
    res.end();
  }
}).listen(port, hostname, () => {
  console.log(`Server running on port ${port}`);
});

推荐阅读