Node.js 编写接口入门学习(GET、POST)

简介: Node.js 编写接口入门学习(GET、POST)

一、简介

$ node -v
  • 安装完成之后,通过 node 直接运行 test.js
// test.js
console.log('Hello Node')
# 命令行执行
$ node test.js

二、简单的 POSTGET 请求封装

  • test.js
// http 库
const http = require('http')
// 参数解析
const querystring = require('querystring')
// 创建服务
const server = http.createServer((req, res) => {
  // req:请求 res:响应
  // 配置响应数据编码格式
  res.setHeader('Content-Type', 'application/json')
  // 请求方式
  const method = req.method
  // 路由地址
  const url = req.url
  // 拆分成请求路由、请求参数
  const strs = url.split('?')
  // 请求路由
  const path = strs[0]
  // 参数
  const query = querystring.parse(strs[1])
  // 组装成响应数据
  const resData = {
    method,
    url,
    path,
    query
  }
  // 判断请求类型
  if (method === 'GET') {
    // 返回响应数据
    res.end(JSON.stringify(resData))
  } else if (method === 'POST') {
    // 请求数据
    let postData = ''
    // 接收数据流 stream
    req.on('data', chunk => {
      // chunk 为二进制数据,所以需要转成字符串,而且数据是一点一点传过来的,也自然需要拼接
      postData += chunk.toString()
    })
    // 接收完成
    req.on('end', () => {
      // 组装数据
      resData.postData = postData
      // 响应数据
      res.end(JSON.stringify(resData))
    })
  } else {
    res.end('请求方式有误!')
  }
})
// 监听端口
// 如果启动报错:Error: listen EADDRINUSE: address already in use :::5000,说明 5000 端口被使用了,换一个端口
server.listen(8000, () => {
  console.log('server running at port 8000')
})
// 运行之后,则可以访问 http://localhost:8000/api/test?id=3
  • 请求效果


三、GET 请求

  • test.js
// http 库
const http = require('http')
// 参数解析
const querystring = require('querystring')
// 创建服务
const server = http.createServer((req, res) => {
  // req:请求 res:响应
  // 获得请求方式
  const method = req.method
  // 请求地址
  const url = req.url
  // 请求参数,传入空也没事
  const query = querystring.parse(url.split('?')[1])
  // 放到请求对象中
  req.query = query
  // 设置响应数据编码格式,这样访问之后就不会出现乱码了
  res.setHeader('Content-Type','text/html; charset=utf-8')
  // 响应数据
  // res.end('Hello Node!并测试中文内容为乱码')
  res.end(JSON.stringify(req.query))
})
// 监听端口
// 如果启动报错:Error: listen EADDRINUSE: address already in use :::5000,说明 5000 端口被使用了,换一个端口
server.listen(8000, () => {
  console.log('server running at port 8000')
})
// 运行之后,则可以访问 http://localhost:8000/?id=3
  • 挂起服务,然后访问 http://localhost:8000/?id=3
$ node test.js
server running at port 8000

四、POST 请求

  • test.js
// http 库
const http = require('http')
// 参数解析
const querystring = require('querystring')
// 创建服务
const server = http.createServer((req, res) => {
  // req:请求 res:响应
  // 设置响应数据编码格式,这样访问之后就不会出现乱码了
  res.setHeader('Content-Type','text/html; charset=utf-8')
  // 获得请求方式
  const method = req.method
  // 是否为 POST 请求
  if (method === 'POST') {
    // POST数据
    let postData = ''
    // 接收数据流 stream
    req.on('data', chunk => {
      // chunk 为二进制数据,所以需要转成字符串,而且数据是一点一点传过来的,也自然需要拼接
      postData += chunk.toString()
    })
    // 接收完成
    req.on('end', () => {
      // 响应数据
      res.end(postData)
      // res.end({ 'msg': '数据接收完毕', 'data': postData })
    })
  } else {
    // 其他请求
    res.end('请使用 POST 请求')
  }
})
// 监听端口
// 如果启动报错:Error: listen EADDRINUSE: address already in use :::5000,说明 5000 端口被使用了,换一个端口
server.listen(8000, () => {
  console.log('server running at port 8000')
})
// 运行之后,则可以访问 http://localhost:8000/?id=3
  • 挂起服务,然后通过 Postman 或 Apifox 访问 http://localhost:8000
$ node test.js
server running at port 8000


目录
打赏
0
0
0
0
268
分享
相关文章
如何学习JavaScript?
如何学习JavaScript?
81 5
JavaScript学习第二章--字符串
本文介绍了JavaScript中的字符串处理,包括普通字符串和模板字符串的使用方法及常见字符串操作方法如`charAt`、`concat`、`endsWith`等,适合前端学习者参考。作者是一位热爱前端技术的大一学生,专注于分享实用的编程技巧。
45 2
JavaScript学习第一章
本文档介绍了JavaScript的基础知识,包括其在网页中的作用、如何通过JavaScript动态设置HTML元素的CSS属性,以及JavaScript中的变量类型(`var`、`let`、`const`)和数据类型(基本数据类型与引用数据类型)。通过实例代码详细解释了JavaScript的核心概念,适合初学者入门学习。
70 1
|
4月前
|
js学习--制作猜数字
js学习--制作猜数字
55 4
js学习--制作猜数字
|
4月前
|
Node.js GET/POST请求
10月更文挑战第6天
54 2
Node.js GET/POST请求
webpack学习五:webpack的配置文件webpack.config.js分离,分离成开发环境配置文件和生产环境配置文件
这篇文章介绍了如何将webpack的配置文件分离成开发环境和生产环境的配置文件,以提高打包效率。
81 1
webpack学习五:webpack的配置文件webpack.config.js分离,分离成开发环境配置文件和生产环境配置文件
如何使用Puppeteer和Node.js爬取大学招生数据:入门指南
本文介绍了如何使用Puppeteer和Node.js爬取大学招生数据,并通过代理IP提升爬取的稳定性和效率。Puppeteer作为一个强大的Node.js库,能够模拟真实浏览器访问,支持JavaScript渲染,适合复杂的爬取任务。文章详细讲解了安装Puppeteer、配置代理IP、实现爬虫代码的步骤,并提供了代码示例。此外,还给出了注意事项和优化建议,帮助读者高效地抓取和分析招生数据。
158 0
如何使用Puppeteer和Node.js爬取大学招生数据:入门指南
node博客小项目:接口开发、连接mysql数据库
【10月更文挑战第14天】node博客小项目:接口开发、连接mysql数据库
|
4月前
|
js学习--制作选项卡
js学习--制作选项卡
50 4
|
4月前
|
js学习--商品列表商品详情
js学习--商品列表商品详情
53 2

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等