Frontend vue axios backend koa2, frontend sends requests without cookie

the subject has just learned node and back-end knowledge. There was a problem when combining the previous todolist written in vue with the back-end code (login section).

Front end Code-vue methods

methods: {
    checkHasLogin () {
      axios.get("/api/login/hasLogin")
        .then((res) => {
          if (res.success) {
            this.username = res.success.msg
            console.log("username ok")
          } else {
            this.username = ""
            console.log("username fail")
            this.$router.replace("/login")
          }
        })
        .catch((err) => { console.log(err) })
    }
},
mounted () {
  console.log("todolist mount")
  this.checkHasLogin()
}

Front end Code-axios

import axios from "axios"

axios.defaults.baseURL = "http://localhost:3000"
axios.defaults.withCredentials = true
axios.defaults.crossDomain = true

export default axios

backend code-app.js

const Koa = require("koa")
const app = new Koa()
const views = require("koa-views")
const json = require("koa-json")
const cors = require("kcors")
const onerror = require("koa-onerror")
const bodyparser = require("koa-bodyparser")
const logger = require("koa-logger")
const session = require("koa-session")

const path = require("path")

const index = require("./routes/index")

app.keys = ["vue koa todo demo"]

const CONFIG = {
  key: "koa:todo",
  maxAge: 86400000,
  overwrite: true,
  httpOnly: true,
  signed: true,
  rolling: false,
  renew: false
}

// error handler
onerror(app)

// 
app.use(cors({
  origin: "http://localhost:8080",
  credentials: true
}))
app.use(session(CONFIG, app))

// middlewares
app.use(bodyparser({
  enableTypes: ["json", "form", "text"]
}))
app.use(json())
app.use(logger())
app.use(require("koa-static")(path.resolve(__dirname, "/public")))

app.use(views(path.resolve(__dirname, "/views"), {
  extension: "pug"
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx)
})

module.exports = app

backend code-login.js

const router = require("koa-router")()
const User = require("../models/user")
const checkLogin = async (ctx, next) => {
  const { name, pwd } = ctx.request.body
  const userDoc = await User.findOne({ userId: name })
  if (userDoc) {
    if (userDoc.userPwd === pwd) {
      // ctx.session = {
      //   userName: userDoc.userId
      // }
      console.log("userId", userDoc.userId)
      ctx.session.userName = userDoc.userId
      console.log("session userId", ctx.session.userName)
      ctx.body = { success: true, msg: "" }
    } else {
      ctx.body = { success: false, msg: "" }
    }
  } else {
    ctx.body = { success: false, msg: "" }
  }
}

const checkHasLogin = async (ctx, next) => {
  console.log(ctx.session.userName)
  if (ctx.session.userName) {
    ctx.body = {
      success: true,
      msg: ctx.session.userName
    }
  } else {
    ctx.body = {
      success: false,
      msg: ""
    }
  }
}

router.get("/hasLogin", checkHasLogin)
router.post("/", checkLogin)

after entering login information, the set-cookie on the server side can be seen, but the front end does not carry Cookie, when it requests again, and there is no Cookie information in the browser"s application

clipboard.png
clipboard.png

Please take a look at it. The question may be a little white, please spray it lightly. no, no, no. Thank you.


what is the port of your node service?


axios does not have cookie by default, so you need to set withCredentials to true .


how does the landlord solve the problem now

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e86a84-46bce.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e86a84-46bce.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?