【问题标题】:File cannot post with Vue.js + axios文件无法使用 Vue.js + axios 发布
【发布时间】:2018-04-20 09:39:52
【问题描述】:

我现在专注于通过 Vue.js axios 将文件上传到后端(node.js)。教程是https://serversideup.net/uploading-files-vuejs-axios/
上传功能:

submitFile(){
            let formData = new FormData();
            formData.append('file', this.file);
            let config = {
              headers:{'Content-Type':'multipart/form-data'}
            };

            axios.post("/parser/upload", formData, config
              ).then(function(){
                console.log('SUCCESS!!');
              })
                .catch(function(){
                  console.log('FAILURE!!');
                });
            },

        handleFileUpload(){
              this.file = this.$refs.file.files[0];
            },

但是当我尝试将一个文件上传到后端时,它一直在 chrome 上显示“无法发布”并且找不到 404。我前端的端口是 8024,后端是 3000。我在 index.js 和 app.js 中设置了代理。
vue 配置中的 index.js:

  // Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
  '/goods':{
      target:'http://localhost:3000'
  },
  '/parser/*':{
      target:'http://localhost:3000',
      changeOrigin: true,
  },
  '/users/*':{
      target:'http://localhost:3000'
  }

},

// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8024, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false

app.js

var indexRouter = require('./routes/index');
var parserRouter = require('./routes/parser');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/parser', parserRouter);

解析器是主路由器。此外,chrome 显示 React URL 是:localhost:8024,但它应该是 localhost:8024/parser/upload 我只是无法弄清楚我的代码的哪一部分出错了。

【问题讨论】:

    标签: node.js vue.js axios


    【解决方案1】:

    你不能做axios.post("/parser/upload"...,因为这将发布到前端,你需要告诉 axios 通过这样做来发布到后端

    axios.post("https://localhost:3000/parser/upload"...

    【讨论】:

    • 呃,我已经设置代理了,让前端连接后端。请参阅我介绍的 index.js。
    • 我明白了。这行得通吗?当您在开发人员工具中检查请求时,它会转到 localhost:3000 吗?
    猜你喜欢
    • 2020-12-26
    • 2021-01-05
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2022-01-26
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多