簡體   English   中英

我想知道如何在 Node.JS 中處理 POST 請求

[英]I want to know how to handle POST requests in Node.JS

好的,所以我想要一個應用程序在端口 8080 或 80 上向我的服務器發送 POST 請求。我不知道如何讓 Node 處理這些請求。 我希望能夠將請求的正文打印到控制台中。

您需要按如下方式創建一個 http 服務器並檢查請求方法。 看一看Nodejs Http Server

http事務剖析

你可以使用express來處理這些操作

var http = require('http');
http.createServer(function (req, res) {

if (req.method == 'POST') {
    let body = [];
    req.on('data', (chunk) => {
      body.push(chunk);
    }).on('end', () => {
       body = Buffer.concat(body).toString();
       // at this point, `body` has the entire request body stored in it as a string
      console.log(body);
    }); 
}

}).listen(8080);

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

//Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.post('/user', urlencodedParser, function(req,res) {
        console.log(req.body.login);
        console.log(req.body.password);
});

app.listen(8080);

其中登錄名密碼是我從表單中獲得的輸入的名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM