美文网首页
解决跨域问题之一

解决跨域问题之一

作者: PharkiLL | 来源:发表于2022-02-28 09:25 被阅读0次

1.(前端)axios 设置withCredentials 为 true

2.在服务端设置Access-Control-Allow-Credentials为 true,设置Access-Control-Allow-Origin到指定请求地址

前端
// 修改跨域请求的代码
btn.onclick = function () {
    axios({
      withCredentials: true, // 配置跨域
      method: "get",
      url: "http://localhost:8000/service",
    }).then((res) => {
      console.log(res);
    });
};
 

node.js
// 在所有路由前增加,可以拦截所有请求
app.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "http://localhost:8000");
  res.header("Access-Control-Allow-Credentials", "true"); // ++ 新增
  next();
}); 

相关文章

网友评论

      本文标题:解决跨域问题之一

      本文链接:https://www.haomeiwen.com/subject/rdxlrrtx.html