node.js - VueJS-Axios:将图像文件上传到 localhost 会出现错误:POST 404(未找到)。为什么?
问题描述
我有一个非常简单的 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") 被解雇但无法超越。
谢谢
解决方案
推荐阅读
- mongodb - 如何取消“查找”中的关系?
- reactjs - Reactjs:如何渲染从道具传递的HTML标签
- computer-science - 乘法位
- android - 后台服务在从 MIUI 中的最近清除时被杀死
- wordpress - .htaccess wordpress 子站点之间的多站点重定向
- android - 当我使用 firebase 中的哈希映射更新我的值时,我当前的活动崩溃了
- php - Fuel\Core\PhpErrorException [警告]:array_key_exists():第一个参数应该是字符串或整数
- python - 有没有办法限制 Ray 对象存储的最大内存使用量
- angularjs - 保护 Angular JS 表达式
- php - 使用laravel中的长度感知分页器搜索结果分页太慢