【问题标题】:OPTIONS 404 on Vue.js file uploadVue.js 文件上传的选项 404
【发布时间】:2019-05-09 04:47:57
【问题描述】:

我已经在我的 express 应用程序中定义了 cors,并且大多数路线都没有这个问题。但是,对于我用来上传图片的特定组件:

<input type="file" class="form-control" @change="imageChagned">

<div  @click="postPhoto">Upload Photo</div>  

方法:

postPhoto: function() {
    console.log('sending photo');
    axios.post( this.BASE_URL + "/profile/addphoto", {
    file: this.image 
    }, this.jwt).then( (res) => { 
    console.log('after photo sent');
    this.image = '';
    console.log(res);
    })
      .catch( (error) => { 

        console.log(error);

      });

},

imageChagned(e) { 
    var reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
    reader.onload = (e) => {
            this.image = e.target.result;    
        }
    } 

我在浏览器中收到此错误:

OPTIONS http://127.0.0.1:3000/profile/addphoto 404 (Not Found)
dispatchXhrRequest @ xhr.js?b50d:178
xhrAdapter @ xhr.js?b50d:12
dispatchRequest @ dispatchRequest.js?5270:59
Promise.then (async)
request @ Axios.js?0a06:51
Axios.(anonymous function) @ Axios.js?0a06:71
wrap @ bind.js?1d2b:9
postPhoto @ AddPhoto.vue?0625:242
invoker @ vue.runtime.esm.js?2b0e:2023
fn._withTask.fn._withTask @ vue.runtime.esm.js?2b0e:1822
addphoto:1 Access to XMLHttpRequest at 'http://127.0.0.1:3000/profile/addphoto' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

这里是接收帖子的路由器:

  router.post('/addphoto',  checkAuth, (req, res)=> {

    console.log('add photo post received');
       let filename = Math.floor(Math.random() * 100000);
  let dir = './uploads/' + req.user.id;
    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }   
    base64String = req.body.file;
    let str = base64String.split(';base64,');
    let base64Image = str[1];
    let extRaw = str[0];
    let ext = extRaw.split('/')[1].toLowerCase();
    let extArray = ['jpg', 'jpeg', 'png', 'gif'];
    const buffer = Buffer.from(base64String.substring(base64String.indexOf(',') + 1));
    fileSizeMB = buffer.length / 1e+6
    //Check file extension
    if (!extArray.includes(ext)) {
      res.status(403).json({msg: 'error: file extention not allowed'})
      return
    };

    //Check file size
    if(fileSizeMB > 5) {
      res.status(403).json({msg: 'error: file is too large'})
      return
    }

    let imgId =  filename + '.' + ext; 
    let filePath = dir + "/" + imgId;
    fs.writeFile( filePath, base64Image, {encoding: 'base64'}, function(err) {
      });
      const photoFields = {};
      photoFields.photos = []
      let p = {}

      p.imgId =  imgId  ;
      p.visible = 'all'
    User.findOne({ _id: req.user.id }).then(user => {
      if (!user.images.profileImg.length > 0 ) {
        user.images.profileImg = p.imgId;
      }

      user.images.photos.push(p);
      user.save().then(()=>{
        console.log('new photo is saved');
        res.json({ images: user.images });
      }).catch(err =>
      console.log(err)
      );

    });


  });

这个问题困扰了我好几个小时,因此非常感谢您提供的修复它的提示。

奇怪的是,该组件工作正常,但在我对代码进行了一些小的更改后它就停止工作了。

【问题讨论】:

  • 有哪些变化?你做的?
  • 我对模式进行了一些更改,但没有对服务器进行更改。太多的改变我无法回溯。

标签: javascript node.js express vue.js axios


【解决方案1】:

如错误所示,方法 OPTIONS 没有名为 /profile/addphoto 的端点。您发布的路线不会受到OPTIONS 请求的影响,因为您指定它只接收POST

OPTIONS 请求用于让请求者知道它被允许如何使用您的 API,因此只需在设置 cors 标头后返回状态 200。我通常通过添加它来拦截向 API 发出的 any OPTIONS 请求。只需在路由开头的某处添加它:

app.use(function(req, res, next) {
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, X-Requested-With, auth_token, X-CSRF-Token, Authorization');
    res.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT, PATCH');
    res.set('Access-Control-Allow-Credentials', 'true');

    // intercept OPTIONS method
    if (req.method === 'OPTIONS') {
        return res.status(200).end();
    }

    next();
});

【讨论】:

  • 感谢您的提示,但在应用您的app.use 之后,我现在得到了POST http://127.0.0.1:3000/profile/addphoto 404 (Not Found)。有什么想法吗?
  • 如果没有看到你的整个路线就很难判断。
  • 我的路线很简单:app.use('/users', users); app.use('/profile', profiles);
  • 仅作记录。 404 POST 错误在清除缓存后消失了。奇怪!
猜你喜欢
  • 2016-08-22
  • 2017-03-05
  • 1970-01-01
  • 2011-07-18
  • 2022-11-05
  • 1970-01-01
  • 2018-09-02
  • 2017-11-29
  • 1970-01-01
相关资源
最近更新 更多