zoukankan      html  css  js  c++  java
  • npm包之accepts---解决不同Accepts请求问题

    前言

    大多时候,我们希望使用请求头中的Accept字段来确定我们接口返回的数据类型,来满足不同格式需求的调用者(防止解析错误)。
    当然还有 字符集、编码、语言等等。
    使用accepts包我们就可以解决这个问题。
    如果没有符合的数据类型,就直接返回 HTTP 406 "Not Acceptable" 错误来告知调用者;

    示例

    var accepts = require('accepts')
    var http = require('http')
     
    function app (req, res) {
      var accept = accepts(req) // 使用request对象创建实例
     
      switch (accept.type(['json', 'html'])) {
        case 'json':
          res.setHeader('Content-Type', 'application/json')
          res.write('{"hello":"world!"}')
          break
        case 'html':
          res.setHeader('Content-Type', 'text/html')
          res.write('<b>hello, world!</b>')
          break
        default:
          // the fallback is text/plain, so no need to specify it above
          res.setHeader('Content-Type', 'text/plain')
          res.write('hello, world!')
          break
      }
     
      res.end()
    }
     
    http.createServer(app).listen(3000) // 创建服务
    

    总结

    1. 同样我们可以应用Express,Koa框架中;
    2. 在Express中,Accept判断已经被封装到了req.accepts()方法中,直接使用就可以了;
    3. 其他请求头类型判断同理;
  • 相关阅读:
    继承实战
    工厂设计模式
    接口匿名内部类
    枚举类
    接口.匿名内部类
    学生信息管理系统(bug)
    System类
    1.1 计算机基础知识 & jdk 安装 & 标识符
    DedeCMS 在子栏目或内容页,调用所在顶级栏目的栏目名
    latex 中 section 标题中如何插入特殊符号
  • 原文地址:https://www.cnblogs.com/xpengp/p/12800634.html
Copyright © 2011-2022 走看看