当前位置:   article > 正文

Access to XMLHttpRequest at……问题出现时怎么办

Access to XMLHttpRequest at……问题出现时怎么办

后端设置

确保在后端正确配置 CORS 中间件,允许跨域请求并支持凭据传递。

假设你使用的是 Express.js,可以这样设置:

  1. const express = require('express');
  2. const cors = require('cors');
  3. const app = express();
  4. // CORS 配置
  5. const corsOptions = {
  6. origin: 'http://localhost:5173', // 允许的前端地址
  7. credentials: true, // 允许发送 cookie
  8. };
  9. app.use(cors(corsOptions));
  10. // 示例路由
  11. app.post('/api/teachers/login', (req, res) => {
  12. const token = tokenEncode(data); // 生成 JWT
  13. res.cookie('token', token, {
  14. maxAge: 30 * 24 * 60 * 60 * 1000, // 30 天
  15. httpOnly: true, // 仅通过 HTTP 访问,防止 XSS 攻击
  16. secure: true, // 仅在 HTTPS 下发送
  17. sameSite: 'None' // 允许跨站点发送 cookie
  18. });
  19. res.json({ message: 'login success' });
  20. });
  21. app.listen(8080, () => {
  22. console.log('Server is running on port 8080');
  23. });

前端请求设置

确保在前端的请求中包含 credentials: 'include',这样可以发送和接收 cookie。

  1. fetch('http://localhost:8080/api/teachers/login', {
  2. method: 'POST',
  3. headers: {
  4. 'Content-Type': 'application/json'
  5. },
  6. credentials: 'include', // 允许发送和接收 cookie
  7. body: JSON.stringify({
  8. // 你的请求数据
  9. name: this.name,
  10. sex: this.sex,
  11. school: this.school,
  12. className: this.className, // 修改为className
  13. phone: this.phone,
  14. password: this.password,
  15. subject: this.array[this.index],
  16. ismaster: this.ismaster
  17. })
  18. })
  19. .then(response => response.json())
  20. .then(data => {
  21. console.log('后端响应结果:', data);
  22. })
  23. .catch(error => console.error('请求失败:', error));

其他注意事项

  1. 确保后端和前端的域名、端口号正确:确保在 CORS 设置中的 origin 与前端请求的地址一致。

  2. 检查预检请求(OPTIONS 请求):有时浏览器会先发送一个预检请求(OPTIONS 请求)来检查服务器是否允许实际请求。如果预检请求失败,实际请求就会被阻止。确保后端正确处理 OPTIONS 请求。
     

    app.options('/api/teachers/login', cors(corsOptions)); // 处理预检请求
    

  3. HTTPS 配置:如果你在开发环境中使用 HTTPS,需要确保 secure 设置为 true。在本地开发环境中,可以暂时设置为 false 进行调试。

通过这些配置,可以解决 CORS 问题,并允许前端正确接收来自后端的 cookie

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/875704
推荐阅读
相关标签
  

闽ICP备14008679号