我正在尝试在Express和React应用程序上设置cookie,Express服务器托管在端口8000上,而React应用程序托管在端口3000上。在服务器端,当我尝试将响应发送到客户端时,我不断获得500: Internal Server Error
。
我认为这是cors的问题,但我不确定是什么。
我的快递服务器代码
const express = require('express'),
cors = require('cors'),
const app = express()
// other requirements and stuff not pertaining to cookies
app.use(require("express-session")({
secret: process.env.LOGIN_SERVER_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: false,
secure: false
}
}));
const corsOptions = {
origin: 'http://localhost:3000',
methods: "GET,HEAD,POST,PATCH,DELETE,OPTIONS",
credentials: true,
allowedHeaders: "Content-Type, Authorization, X-Requested-With"
}
app.options("*", cors(corsOptions))
app.get("/api/cookie", cors(corsOptions), (req, res) => {
const options = {
secure: false,
httpOnly: false,
domain: "http://localhost:3000"
}
return res
.cookie("cookieName", "cookieValue", options)
.status(200)
.send("cookie sent")
})
我试图在componentDidMount()生命周期方法中的App.js文件中获取cookie,然后console.logging响应,但响应只是我正在谈论的500: Internal Server Error
。我也在两者之间设置了代理。
这是我的React App组件
import React from 'react'
class App extends React.Component {
state = {}
componentDidMount = () => {
fetch('/api/cookie', {credentials:'include'})
.then(response => {console.log(response)})
.catch(err => {console.log(error)})
}
render() {
return (
// routes to pages
)
}
}