对节点服务器的 Axios GET 请求永远不会返回登录用户,在浏览器中手动访问相同的路由会返回



我有一个节点服务器在localhost:8000上运行,它会在/user吐出当前登录的用户。现在在我的前端localhost:8001我想检索该用户。

如果我在浏览器中手动转到localhost:8000/user,只要我已登录,我就会取回用户。每当我注销时,都会返回一个空字符串。目前为止,一切都好。

但是:每当我从前端localhost:8000/user发送请求时,我都会得到空字符串。所以它正在工作(我没有收到任何错误,状态代码为 200 (,但似乎我的前端不知道我已登录/我的后端没有意识到我已登录。

前端

axios.get("localhost:8000/user").then(res => {
    console.log(res)
  }) //this works, but always behaves like there is no current 
     //user i.e. that I am logged-out

后端

//imports here, then:    
passport.use(
  new Auth0Strategy(
    {
      domain: "bla.eu.auth0.com",
      clientID: "afjgnrtkngewmofmwlefmlwems",
      clientSecret:
        "jngnsknkankjangkjangjknKJJKGKAHBJVvgjvVgjVbhJBjhbJbj",
      callbackURL: "http://localhost:8000/callback",
      audience: "https://bla.eu.auth0.com/userinfo",
      responseType: "code",
      scope: "openid email profile",
    },
    function(accessToken, refreshToken, extraParam, profile, done) {
      return done(null, profile)
    }
  )
)
passport.serializeUser(function(user, done) {
  done(null, user)
})
passport.deserializeUser(function(user, done) {
  done(null, user)
})
const app = express()
app.use(cors({ origin: "http://localhost:8001" }))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(
  session({ secret: "secret_key", resave: true, saveUninitialized: true })
)
app.use(passport.initialize())
app.use(passport.session())
app.use(function(req, res, next) {
  res.locals.loggeedIn = false
  if (req.session.passport && typeof req.session.passport.user !== undefined) {
    res.locals.loggedIn = true
  }
  next()
})
app.get("/", function(req, res, next) {
  res.send("Root")
})
app.get(
  "/login",
  passport.authenticate(
    "auth0",
    {
      domain: "bla.auth0.com",
      clientID: "kafmkafmkamfkamfka",
      redirectUri: "http://localhost:8000/callback",
      audience: "https://bla.auth0.com/userinfo",
      responseType: "code",
      scope: "openid email profile",
    },
    function(req, res, next) {
      res.redirect("/")
    }
  )
)
app.get("/logout", function(req, res, next) {
  req.logout()
  res.redirect("/")
})
app.get(
  "/callback",
  passport.authenticate("auth0", {
    failureRedirect: "/failure",
  }),
  function(req, res) {
    res.redirect("/user")
  }
)
app.get("/user", function(req, res, next) {
  res.send(req.user)
})
app.get("/failure", function(req, res, next) {
  res.send("Failure")
})
app.listen(8000, function() {
  console.log("running")
})
有什么东西是

我在这里没有得到的吗?在localhost:8000/user访问浏览器并向"本地主机:8000/用户"发出 axios 请求是不一样的吗?

默认情况下,

Axios不发送cookie。您必须通过将"凭据"选项设置为 true 来设置使会话启用 Cookie 才能正常工作。

axios.get("localhost:8000/user", { withCredentials: true } ).then(res => {
    console.log(res)
  }) 

最新更新