请问不用框架 Nodejs我如何处理不同的get和post

请问不用框架 Nodejs我如何处理不同的get和post

原生nodejs里该如何理相同路径下用get和post提交的不同的get和post处理方法

思路:用requset的header里取区分get和post或其他方式,不知是不是这样实现的

比如 if(req.url.pathname==’/reg’) { if(req.method.处理get) 处理get

if(req.method.post) 不是是否有这样的方式 百度了http协议 貌似req会有method 处理post

if(req.xxx.XXX) 处理其他XXX }

高手解答下 或者直接给出具体的问题的解决思路下 !


5 回复

当然可以。在不使用任何框架的情况下,Node.js 提供了原生的 HTTP 模块来处理 HTTP 请求。你可以通过检查请求的方法(GETPOST)来分别处理不同的逻辑。

以下是一个简单的示例代码,展示了如何处理 /reg 路径下的 GETPOST 请求:

const http = require('http');

const server = http.createServer((req, res) => {
    // 设置响应头
    res.writeHead(200, { 'Content-Type': 'text/html' });

    // 检查请求路径是否为 '/reg'
    if (req.url === '/reg') {
        // 检查请求方法是否为 GET
        if (req.method.toUpperCase() === 'GET') {
            // 处理 GET 请求
            res.end('<h1>这是 GET 请求</h1>');
        } else if (req.method.toUpperCase() === 'POST') {
            // 处理 POST 请求
            let body = [];
            req.on('data', chunk => {
                body.push(chunk);
            }).on('end', () => {
                body = Buffer.concat(body).toString();
                // 在这里处理 POST 数据
                res.end(`<h1>这是 POST 请求,收到的数据: ${body}</h1>`);
            });
        } else {
            // 其他请求方法
            res.writeHead(405, { 'Content-Type': 'text/plain' });
            res.end('Method Not Allowed');
        }
    } else {
        // 其他路径
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

// 监听端口
server.listen(3000, () => {
    console.log('服务器运行在 http://localhost:3000');
});

解释

  1. 创建 HTTP 服务器

    • 使用 http.createServer() 创建一个 HTTP 服务器,并传入一个回调函数来处理每个请求。
  2. 设置响应头

    • 使用 res.writeHead() 设置响应的状态码和响应头。
  3. 检查请求路径

    • 使用 req.url 检查请求路径是否为 /reg
  4. 处理不同请求方法

    • 使用 req.method 检查请求方法是否为 GETPOST
    • 对于 GET 请求,直接返回响应。
    • 对于 POST 请求,监听 'data' 事件来收集请求体中的数据,并在 'end' 事件中处理这些数据。
    • 如果请求方法不是 GETPOST,则返回 405 Method Not Allowed
  5. 处理其他路径

    • 如果请求路径不是 /reg,则返回 404 Not Found

这个示例展示了如何在不使用任何框架的情况下,处理不同的 HTTP 方法和路径。希望这能帮助你理解和实现你的需求。


0.8之前有request.method的api,之后的请教高手

不太懂呀 亲 刚用ff浏览器firebug看了下 post和get提交的header信息 貌似就多了个content-type字段信息 是用这个来区分 那如何区别post和其他呢 是firebug只显示了部分吗 ?

Nodejs 原生的接受 Http 请求的方法是: Class: http.Server 的

Event: ‘request’# function (request, response) { }。

而这个request 是:http.IncomingMessage。

而这个IncommingMessage 包含下面这个值。

message.method# Only valid for request obtained from http.Server.

The request method as a string. Read only. Example: ‘GET’, ‘DELETE’.

上面的内容都在这个页面: http://nodejs.org/api/http.html#http_message_method

在 Node.js 中处理不同 HTTP 方法(如 GET 和 POST)可以使用内置的 http 模块。你可以通过检查请求的 method 属性来区分这些方法,并根据需要处理不同的逻辑。

以下是一个简单的示例代码,展示如何处理 /reg 路径下的 GET 和 POST 请求:

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.url === '/reg') {
        if (req.method.toUpperCase() === 'GET') {
            // 处理 GET 请求
            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.end('Handling GET request');
        } else if (req.method.toUpperCase() === 'POST') {
            // 处理 POST 请求
            let body = [];
            req.on('data', chunk => {
                body.push(chunk);
            }).on('end', () => {
                body = Buffer.concat(body).toString();
                res.writeHead(200, { 'Content-Type': 'text/plain' });
                res.end(`Handling POST request with data: ${body}`);
            });
        } else {
            // 其他 HTTP 方法
            res.writeHead(405, { 'Content-Type': 'text/plain' });
            res.end('Method Not Allowed');
        }
    } else {
        // 处理其他路径
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server is running on port 3000');
});

解释

  1. 创建服务器:使用 http.createServer 创建一个 HTTP 服务器。
  2. 检查 URL 和方法
    • 如果请求的 URL 是 /reg 并且方法是 GET,则处理 GET 请求。
    • 如果请求的 URL 是 /reg 并且方法是 POST,则处理 POST 请求。
    • 对于其他 HTTP 方法,返回 405 Method Not Allowed。
    • 对于其他 URL,返回 404 Not Found。
  3. 处理 POST 请求:使用 req.on('data', ...) 监听数据流,并在 req.on('end', ...) 中将所有数据拼接起来。
  4. 响应客户端:使用 res.writeHead 设置响应头,并使用 res.end 发送响应内容。

通过这种方式,你可以轻松地处理不同 HTTP 方法的请求。

回到顶部