【发布时间】:2022-02-11 17:07:45
【问题描述】:
我在 node express 中创建了 API,并在端口 :8000 上运行它,我通过端口 :3000 上的简单 CRA 使用 API。我已经通过设置 httpOnly cookie 创建了注册和登录。此外,我已经使用中间件来检查每个端点,以验证它是否具有该令牌。
当我通过 Thunder/Postman 进行测试时,一切正常,登录后我得到了 cookie 作为响应,我将该 cookie 设置为身份验证令牌并发出获取数据的请求,然后我就得到了数据。
当我通过 React 前端登录时,它会成功,我可以在网络选项卡中看到我收到了 cookie 作为响应。但是当我向受保护的端点发出请求时,该请求中没有 cookie(我在服务器上记录传入请求并比较使用 Thunder/Postman 客户端和通过浏览器中的应用程序发出的请求)。
我用的是 axios,我把{withCredentials: true} 放了还是不行。我用过withAxios钩子,也不管用。
服务器
index.js
...
const app = express()
app.use(cors({
credentials: true,
origin: 'http://localhost:3000',
}));
...
控制器/User.js
...
const loginUser = async(req, res) => {
const body = req.body
const user = await User.findOne({ email: body.email })
if(user) {
const token = generateToken(user)
const userObject = {
userId: user._id,
userEmail: user.email,
userRole: user.role
}
const validPassword = await bcrypt.compare(body.password, user.password)
if(validPassword) {
res.set('Access-Control-Allow-Origin', req.headers.origin);
res.set('Access-Control-Allow-Credentials', 'true');
res.set(
'Access-Control-Expose-Headers',
'date, etag, access-control-allow-origin, access-control-allow-credentials'
)
res.cookie('auth-token', token, {
httpOnly: true,
sameSite: 'strict'
})
res.status(200).json(userObject)
} else {
res.status(400).json({ error: "Invalid password" })
}
} else {
res.status(401).json({ error: "User doesn't exist" })
}
}
...
middleware.js
...
exports.verify = (req, res, next) => {
const token = req.headers.authorization
if(!token) res.status(403).json({ error: "please provide a token" })
else {
jwt.verify(token.split(" ")[1], tokenSecret, (err, value) => {
if(err) res.status(500).json({error: "failed to authenticate token"})
req.user = value.data
next()
})
}
}
...
路由器.js
...
router.get('/bills', middleware.verify, getBills)
router.post('/login', loginUser)
...
客户
src/components/LoginComponent.js
...
const loginUser = (e) => {
setLoading(true)
e.preventDefault()
let payload = {email: email, password: password}
axios.post('http://localhost:8000/login', payload).then(res => res.status === 200
? (setLoading(false), navigate('/listbills')) : navigate('/register'))
}
...
src/components/ListBills.js
...
useEffect(() => {
fetch('http://localhost:8000/bills', {
method: 'get',
headers: {'Content-Type': 'application/json'},
credentials: 'include',
})
.then(response => {console.log(response)}).catch(err => console.log(err));
}, [])
...
我也试过了:
axios.get('http://localhost:8000/bills',{withCredentials: true})
.then((data) => console.log(data))
.then((result) => console.log(result))
.catch((err) => console.log('[Control Error ] ', err))
}
和
const [{ data, loading, error }, refetch] = useAxios(
'http://localhost:8000/bills',{
withCredentials: true,
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}})
Console.log 错误:
登录后,我会在“网络”选项卡中看到:
但是当我想访问列表时:
=== 更新 ===
所以问题的原因是没有在请求标头中传递 httpOnly cookie。这是我正在使用的中间件的日志:
token undefined
req headers auth undefined
req headers {
host: 'localhost:8000',
connection: 'keep-alive',
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
'sec-ch-ua-platform': '"macOS"',
'content-type': 'application/json',
accept: '*/*',
origin: 'http://localhost:3000',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
referer: 'http://localhost:3000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9,hr;q=0.8,sr;q=0.7,bs;q=0.6,de;q=0.5,fr;q=0.4,it;q=0.3'
}
令牌是从headers.authorization 读取的,但从headers 的日志中它不存在,因此我的请求无法获得授权。
还是不行。
【问题讨论】:
-
尝试使用cookie-parser中间件进行快递
-
@wald3 是的,我正在使用它,在
const app = express()下直接调用仍然无法正常工作,不管我尝试什么,授权 cookie、不记名令牌无论你怎么称呼它都不会得到与请求一起发送到服务器
标签: javascript node.js reactjs express cross-domain