我的MERN申请未能在浏览器上储存会议。 在Heroku公司的赞助下,客户由Vercel主办。 当我转向当地招待所时,它按预期运作,但在部署时却未能储存任何会议。 如果我试图在用户中登录,它将通过认证,但它在我的浏览器上赢得一个会议。
我发现这一错误:
Access to XMLHttpRequest at https://myapp-backend.herokuapp.com/user from origin https://myapp-client.vercel.app has been blocked by CORS policy: The value of the Access-Control-Allow-Credentials header in the response is which must be true when the request s credentials mode is include . The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
这里是我所拥有的。
服务器:
const url = process.env.MONGO_DB_URL
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
const db = mongoose.connection
db.on( error , console.error.bind(console, connection error ))
db.once( open , () => {
console.log( connected to mongo database )
})
const app = express()
app.set( views , path.join(__dirname, views ))
app.use(
mongoSanitize({
replaceWith: _ ,
})
)
app.use(helmet())
app.use(express.json())
app.use(
cors({
origin: [ http://192.168.1.14:3000 , https://myapp-client.vercel.app ],
credentials: true,
})
)
app.use(express.static(path.join(__dirname, public )))
// express session middleware
const store = MongoStore.create({
mongoUrl: url,
secret: process.env.MONGO_SECRET,
touchAfter: 24 * 60 * 60,
})
store.on( error , err => {
console.log(err)
})
app.use(
session({
store,
name: rfts ,
secret: process.env.MONGO_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
expires: Date.now() + 1000 * 60 * 60 * 24 * 3,
maxAge: 1000 * 60 * 60 * 24 * 3,
httpOnly: true,
secure: true,
})
)
app.use(cookieParser(process.env.COOKIE_SECRET))
// passport middleware
app.use(passport.initialize())
app.use(passport.session())
passport.use(new LocalStrategy(User.authenticate()))
passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`listening on port ${PORT}`)
})
在客户方面,我利用这向服务器发出电话:
import axios from axios
const macUrl = http://192.168.1.14:3001
const localUrl = http://localhost:3001
const herokuUrl = https://myapp-backend.herokuapp.com
const axiosCall = axios.create({
baseURL: herokuUrl,
withCredentials: true,
})
export default axiosCall
纽约市的建议将受到高度赞赏。