VueJS-Axios:将图像文件上传到本地主机会出现错误:POST 404(未找到)。为什么?

时间:2019-07-08 14:28:52

标签: node.js vue.js axios

我有一个非常简单的VueJS Axios应用程序,用于了解通过Axios上传文件的情况,但是该文件未保存到http://localhost/upload目录中。

我遇到2个错误:

POST http://localhost:8080/upload 404 (Not Found)

createError.js?f777:16 Uncaught (in promise) Error: Request failed with status code 404
    at createError (eval at <anonymous> (build.js:1359), <anonymous>:16:15)
    at settle (eval at <anonymous> (build.js:1442), <anonymous>:17:12)
    at XMLHttpRequest.handleLoad (eval at <anonymous> (build.js:1338), <anonymous>:59:7)

这是完整的代码:

<template>
  <div id="app">
    <input type="file" @change="getFile">
    <button @click="uploadFile">Upload file</button>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  name: "App",

  data() {
    return {
      selectedFile: null
    }
  },

  methods: {
    getFile() {
      let file = event.target.files[0]
      this.selectedFile = file
    },
    uploadFile() {
        let fd = new FormData()
        fd.append('image', this.selectedFile, this.selectedFile.name)
        axios.post('/upload', fd)
          .then(res => {
              console.log(res);
          })
    }
  }
}
</script>

已更新

服务器端代码(formidable.js)

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');

http.createServer(function (req, res) {
  res.setHeader("Access-Control-Allow-Origin", "*")
  res.setHeader("Content-Type", 'text/html');
  console.log("TRIGGERED");
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/Admin/Desktop/uploadTest/' + files.filetoupload.name;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(9090);

更新的客户端:

<template>
  <div id="app">
    <input type="file" @change="getFile">
    <button @click="uploadFile">Upload file</button>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  name: "App",

  data() {
    return {
      selectedFile: null
    }
  },

  methods: {
    getFile() {

      let file = event.target.files[0]
      this.selectedFile = file
    },
    uploadFile() {
        let fd = new FormData()
        fd.append('myImg', this.selectedFile, this.selectedFile.name)
        axios.post('http://localhost:9090/formidable', fd)
          .then(res => {
              console.log(res);
          })
    }
  }
}
</script>

服务器端代码的问题是我不知道如何检索发送到服务器的文件数据。此console.log(“ TRIGGERED”)被触发,但不能超过该值。

谢谢

0 个答案:

没有答案