11 ~ express ~ solve the problem of error cookie Chinese

Note the use of cookies Package:
1, the cookie is not a Chinese, if there is Chinese, the error will be
2, cookie is mounted in the form of middleware directly to the req object, then some cookies method, req.cookies there, the same
cookie is an object, you need JSON.stringify; 

3, coding uses the encodeURI ( "required content encoded")
4, using the decoded decodeURI ( "content to be decoded")

 

First, coding /router/api.js

try {
  req.cookies.set("userInfo", encodeURI(JSON.stringify({
  _id: userInfo._id,
  username: userInfo.username
})))

} catch (e) {
  console.log(e)
}

 

Second, the decoding app.js

app.use((req, res, next) => {
  var cookies = new Cookies(req,res)
  req.userInfo = {}
  if (req.cookies.get("userInfo")) {
    try {
      var userInfo = req.cookies.get("userInfo")
      req.userInfo = JSON.parse(decodeURI(userInfo))
      console.log ( 'app.js, successful parse userinfo-')
      console.log(req.userInfo)
    } catch (e) {
      console.log ( "app.js, cookie information parsing failed")
    }
}

    next()
}
 

Guess you like

Origin www.cnblogs.com/500m/p/11003507.html