我有一个使用 Reactjs 作为客户端和 node express 作为服务器端的应用程序。我在服务器的标题中发送烹饪,cookie 显示在浏览器上,但它们没有被保存,但它们被保存了我使用 Insomnia 我已经阅读了很多关于此的问题和答案,但实际上并没有解决问题。下面是我的设置
** 客户端示例代码 ----------- **
export const BusinessLogin = (header,account) => axios.post(`${businessURI}/login`, account, header) //
export const LoginBusiness = (account) => async (dispatch) => {
const config = {
headers :{
'Content-Type': 'application/json'
},
credentials: "include",
withCredentials: true
}
try {
const data = await api.BusinessLogin(config,account)
console.log(data)
dispatch({type:LOGIN_BUSINESS, payload: data })
console.log(data)
} catch (error) {
console.log(error.message)
}
}
** 服务器端索引文件 ------------ **
app.use(cors({
origin:'http://localhost:3000/',
credentials: true
}));
app.use(function(req, res, next) {
//client is hosted at '127.0.0.1:3000'
res.header('Access-Control-Allow-Origin', '127.0.0.1:3000');
// res.header('XMLHTTPRequest','http://127.0.0.1:3000/')
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
res.setHeader('Access-Control-Expose-Headers', 'x-pagination, Content-Length');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
import business from './routes/business.js';
app.use('/buss', business)
// Libraries
import cors from 'cors';
import cookieParser from 'cookie-parser'
** 服务器端路由器文件 ----------- **
// different libries tried
import cookieParser from 'cookie-parser'
import cookie from 'cookie'
export const Login = async (req, res) => {
const {email, password} = req.body;
const new_account = req.body;
const {cookies} = req
// console.log("cookies",req.sessionStore)
console.log("cookies",req.cookies)
// console.log(req)
const test_cookies = cookie.parse(req.headers.cookie || '');
console.log(test_cookies)
// console.log( req)
if(!email || !password ) return res.status(400).json('fill all field')
try {
await CreateBusiness.findOne({email})
.then(account => {
if(!account) return res.status(400).json({msg:"The email or password you enter does not match account"})
//Validate password with exiting password
bcrypt.compare(password, account.password)
.then(isMatch => {
if(!isMatch) return res.status(400).json({msg: "invalid credentials "})
//user match,
jwt.sign(
{ id: account._id },
Jwt_secret,
{ expiresIn: 3600 }, //last for hour
(error, token) => {
if(error) throw error;
const cookies = {
maxAge: 3600,
httpOnly: false,
sameSite:false,
// secure: true // activate during deployment
}
// trying different methods of setting cookis
res.cookie('accessToken', '474949',cookies)
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
res.setHeader('Access-Control-Allow-Credentials', 'true')
res.setHeader('Set-Cookie', cookie.serialize('name', 'just tetsing the cooki', {
httpOnly: true,
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
res.status(201).cookie('access_token', 'Bearer ' + token, cookies)
res.json({
token,
account,
})
// res.status(200).json(res)
}
)
})
})
} catch (error) {
res.status(209).json({message: error.message})
}
}
我尝试过的其他事情
在阅读了类似的问题后,一些建议设置 //axios.defaults.withCredentials = true,
但每次我都会有一个 cors 错误,即使我已经如图所示进行了 cors 配置,尽管我已经withCredentials: true
在配置中添加了。我也使用了这个cors 扩展,但 cookie 仍然没有保存在浏览器上。
你认为是什么导致他们不保存,我能做些什么来解决它?谢谢你的时间。