http--nodejs原生web服务

 

创建http服务

const http = require('node:http')
const url = require('node:url')

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


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

 

区分请求方法 

例如常见的 POST、GET

req表示前端的入参(请求参数)。 res 表示后端的出参 (返回参数)

http.createServer((req, res) => {
  //通过method 就可以了
 if (req.method === 'POST') {
 
  } else if (req.method === 'GET') {
  
  }

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

 

完整代码

 

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



http.createServer((req, res) => {
  const {pathname,query} = url.parse(req.url,true);

  if(req.method === "POST"){
      if(pathname === "/login"){
        res.statusCode = 200
        let data = ''
        req.on('data', (chunk) => {
          data += chunk
        })

        req.on('end', () => {
           res.statusCode = 200
           res.setHeader('Content-Type', 'application/json')
           res.end(data)
        })
      }else{
        res.statusCode = 404
        res.end("404")
      }

    // res.end("POST")
  }else if(req.method === "GET"){

    if(pathname === "/get"){
      console.log(query)
      res.end("GET")
    }else{
      res.statusCode = 404
      res.end("404")
    }
  }

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

 

 

 

介绍一下vsCODE 插件 :REST Client

减配版的api 测试工具。例如 apiPost. postman

 

posted @ 2025-03-15 19:11  蜗牛般庄  阅读(9)  评论(0)    收藏  举报
Title
页脚 HTML 代码