跨域报错

文件上传

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/jquery.min.js"></script>
    <script src="../js/401.js"></script>
</head>
<body>
    <input type="file" name="" id="upload" >
    <button id="btn">确认上传</button>
    <img src="http://localhost:3000/img/upload.png" alt="" width="100px" height="100px">
</body>
</html>
<script>
    $(function(){

        //确认上传
        $("#btn").click(function(){
            $.ajax({
                url:"/users/upload_sure",
                type:"post",
                success(res){
                    if(res.code==200){
                        alert("上传成功")
                    }
                }
            })
        })
        //预上传
        $("#upload").change(function(){
            let files=this.files;
            let fd=new FormData();
            //如果是单个文件
            //参数1:和后端匹配
            //参数2:文件对象
            fd.append("file",files[0])
            //如果是传递多个文件
            // for(let i=0;i<files.length;i++){
            //     fd.append("file",files[i])
            // }
            $.ajax({
                url:"/users/upload_temp",
                type:"post",
                data:fd,
                contentType:false,
                processData:false,
                success(res){
                    $("img").attr("src","http://localhost:3000/temp/"+res.file.filename)
                }
            })
        })
    })
</script>

后端:文件上传

let {uploadFiles, moveFiles, deleteFiles}=require('../utils/handleFiles')

//临时上传
let filename=""
async function upload_temp(req, res, next) {
  let upload=uploadFiles()
  upload(req,res,err=>{
     if(!err){
         //成功之后
         let file=req.files[0];
         //赋值filename用于确认上传
         filename=file.filename;
         res.send({
          code:200,
          file
         })
     }else{
        res.send({
          code:500
        })
     }
  })
}

//确认上传
async function upload_sure(req, res, next) {
  let fromPath="./public/temp";
  let toPath="./public/img"
  let obj={
    fromPath, toPath, filename
  }
  //移动
  moveFiles(obj)
  //删除
  deleteFiles("./public/temp")

  //操作数据库

   res.send({
    code:200
   })

}

跨域

跨域报错

Access to XMLHttpRequest at 'http://localhost:3000/users/login?username=&password=' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

浏览器的同源策略

为了安全性

同源:协议、IP地址、端口port 三个东东必须一样,只要有一个或多个不一样,则不同源

不同源只针对以下情况报错:
1 ajax 不能发送成功
2 cookie 不能获取
3 dom不能操作

http://192.168.13.13:8080/aa/bb...

以下均为跨域
https://192.168.13.13:8080/aa/bb...
http://192.168.13.14:8080/aa/bb...
http://192.168.13.13:8081/aa/bb...

解决跨域问题

1 jsonp (只支持get提交)


原理:利用 src属性不受跨域影响而实现

前端:
$(function(){
            $.ajax({
                url:"http://localhost:3000/stus/getStus",
                dataType:"jsonp",
                success(res){
                    console.log(res);
                }
            })
        })
后端:
  res.jsonp({
    code: 200,
    stus
  })
}



2 cors (支持所有提交)

跨域资源共享:在服务器端设置允许跨域 (后端处理)

app.js

var allowCrossDomain = function (req, res, next) {
  // 设置允许跨域访问的请求源(* 表示接受任意域名的请求)
  res.header("Access-Control-Allow-Origin", "*");
  // 设置允许跨域访问的请求头
  res.header("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept,Authorization");
  // 设置允许跨域访问的请求类型
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // 同意 cookie 发送到服务器(如果要发送cookie,Access-Control-Allow-Origin 不能设置为星号)
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
};




//代表public下的静态资源路径
app.use(express.static(path.join(__dirname, 'public')));

//允许跨域
app.use(allowCrossDomain);

//拦截生效
//  app.use(jwtAuth)

//配置一级路由
app.use('/users', usersRouter);
app.use('/stus', stusRouter);
app.use('/test', testRouter);
app.use('/clas', clasRouter);

3 配置代理服务器(nginx)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值