是的,我知道有很多问题,但遗憾的是,没有答案能帮助我.

我在Chrome上,使用的是JUJS和VueJs 3.我有一个基本的应用程序,我可以"登录",它带我到另一个页面.从字面上讲,我想做的就是在会话中保存用户名,这样我就知道谁登录了,但它不保存后的帖子请求.下次我想得到数据的时候就没了.我知道这可能是cookies 的问题,但我不知道还能try 什么.

我试着确保它们在同一个主机上,可能所有可用的cookie选项,使用不同的主机,并将请求保存在post请求中作为一个promise .什么都不起作用.

Index.js

require("dotenv").config();
var Express = require("express");
const session = require('express-session');
const mongoose = require("mongoose");
const { User, Note, Gift } = require("./models");
var cors = require("cors");

var app = Express();
app.use(Express.json());
const corsOptions = {
    origin: 'http://localhost:8080',  //Your Client, do not write '*'
    credentials: true,
};
app.use(cors());
app.use(session({
    secret: 'secret-key',
    resave: false,
    saveUninitialized: false,
    cookie: { secure: false, sameSite: 'none', maxAge: 60000 }
  }));

var CONNECTION_STRING = process.env.DATABASE_URL;
var DATABASENAME="gifttracker";

app.listen(5038, () => {
    mongoose.connect(CONNECTION_STRING,{
        dbName: DATABASENAME,
      }).then(() => {
        console.log('Mongo DB Donnection Successful');
    }).catch((err) => {
        console.log('Error connecting to MongoDB: ', err)
    });
})

app.get('/', (req, res) => {
    const sessionData = req.session;
    console.log("get", sessionData);
    res.send(sessionData).status(200);
});


app.post('/api/createUser', async (req, res) => {
    const newUser = new User({ ...req.body });
    const createdUser = await newUser.save();
    console.log("createUser", createdUser);
    req.session.isLoggedIn = true;
    req.session.username = createdUser.username;
    req.session.save();
    res.send(req.session).status(200);
})

vue.config.js代理,以便两者都在同一台主机上

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: [
    'quasar'
  ],

  pluginOptions: {
    quasar: {
      importStrategy: 'kebab',
      rtlSupport: false
    }
  },
  devServer:{
    host: 'localhost',
    hot: true,
    port: 8080,
    proxy: { //https://cli.vuejs.org/guide/html-and-static-assets.html#disable-index-generation
      '/api/': { //web sockets
        target: 'http://localhost:5038',
        secure: false,
        ws: true
      },
    }
  }
})

vue—当我刷新这个页面时,get请求应该包含session. username,但没有.

<template>
  <div class="login">
    <h1>Login</h1>
    <div>
      <input v-model="form.name" required/>
      <input v-model="form.username" required/>
      <input v-model="form.password" type="password" required/>
      <input v-model="form.email"/>
      <input v-model="form.birthday"/>
      <button @click="addUser()">Create Account</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
const API_URL="http://localhost:8080/";
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      form: {
        name: null,
        username: null,
        password: null,
        email: null,
        birthday: null
      }
    }
  },
  methods: {
    async addUser() {
      console.log("USER: ", this.form);
      axios.post(API_URL+"api/createUser", this.form).then((user) => {
        console.log("user created", user);
        this.$router.push("Dashboard");
      }).catch((err)=> {
        console.log("err",err);
      })
      this.getSessionData();
    },
    async getSessionData() {
      axios.get(API_URL, {credentials: "include"}).then((res) => {
        console.log("res", res);
        if (res.username) {
          this.loggedIn = true;
          this.username = res.username;
        }
      })
    },
  }
}
</script>

推荐答案

当您收到服务器的响应时,我认为您需要使用res.data访问响应数据:

axios.get(API_URL, { withCredentials: true })
  .then((res) => {
    console.log("res", res);
    if (res.data.username) {
      this.loggedIn = true;
      this.username = res.data.username;
    }
  })

另外,try 在.then()块内移动getSessionData:

async addUser() {
      console.log("USER: ", this.form);
      axios.post(API_URL+"api/createUser", this.form).then((user) => {
        console.log("user created", user);
        this.getSessionData();
        this.$router.push("Dashboard");
      }).catch((err)=> {
        console.log("err",err);
      })
    }

希望这对你有帮助!

Javascript相关问答推荐

React对话框模式在用户单击预期按钮之前出现

Phaser框架-将子对象附加到Actor

基于变量切换隐藏文本

如何从一个列表中创建一个2列的表?

将现场录音发送到后端

如何从调整大小/zoom 的SVG路径定义新的d属性?""

我的服务工作器没有连接到我的Chrome扩展中的内容脚本.我该怎么解决这个问题?

Webpack在导入前混淆文件名

如何在Bootstrap中减少网格系统中单个div的宽度

我想使用GAS和HTML将从Electron 表格中获得的信息插入到文本字段的初始值中

用于部分字符串的JavaScript数组搜索

如何组合Multer上传?

Node.js API-queryAll()中的MarkLogic数据移动

在渲染turbo流之后滚动到元素

P5JS-绘制不重叠的圆

为什么在运行于<;img>;事件处理程序中的JavaScript中x和y是不可变的?

如何在Firebase中读取对象的特定字段?

脚本语法错误只是一个字符串,而不是一个对象?

在点击链接后重定向至url之前暂停

暂停后只有一次旋转JS