CORS中间件

  1. npm install cors --save
  1. const cors = require('cors')
  2. const app = express()
  3. app.use(cors({credentials: true, origin: true}))

origin Access-Control-Allow-Origin 字段必选Boolean : set origin to true to reflect the request origin, as defined by req.header(‘Origin’), or set it to false to disable CORS.

credentials Access-Control-Allow-Credentials 该字段可选。值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。 CORS请求默认不发送Cookie和HTTP认证信息。 如果要把Cookie发到服务器,一方面要服务器同意,指定Access-Control-Allow-Credentials: true 另一方面,开发者必须在AJAX请求中打开withCredentials属性。 var xhr = new XMLHttpRequest(); xhr.withCredentials = true; 否则,即使服务器同意发送Cookie,浏览器也不会发送


解析中间件

  1. app.use(express.json())

Express框架默认使用body-parser作为请求体解析中间件 express.json()函数是Express中的内置中间件函数。 它使用body-parser解析带有JSON有效负载的传入请求


请求日志中间件

  1. npm install morgan --save
  1. const morgan = require('morgan')
  2. const app = express()
  3. app.use(morgan('tiny'))

Morgan是一个node.js关于http请求的日志中间件 在终端打印日志 每次http请求,express实例都会输出日志,并且使用一致的格式 tiny : The minimal output. :method :url :status :res[content-length] - :response-time ms