Axios请求
handleUpload = e => {
e.preventDefault();
let files = this.state;
console.log(files);
let formdata = new FormData();
//for(var x = 0; x<files.length; x++) {
formdata.append("file", files);
//}
for (var key of formdata.entries()) {
console.log(key[0] + ", " + key[1]);
}
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
}
};
axios
.post(
"http://localhost:8081/api/uploadMultipleCsvFiles",
formdata,
config
// headers: {'Content-Type': 'application/x-www-form-urlencoded'}
)
.then(res => console.log(res))
.catch(err => console.log(err));
};
这是回应
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {url: "http://localhost:8081/api/uploadMultipleCsvFiles", method: "post", data: FormData, headers: {…}, transformRequest: Array(1), …}
data: ""
headers: {content-length: "0"}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: "OK"
__proto__: Object
server.js文件
const express = require('express')
const bodyParser= require('body-parser')
const multer = require('multer');
var cors = require('cors')
const app = express();
app.use(bodyParser.json())
app.use(cors())
//CREATE EXPRESS APP
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})
var upload = multer({ storage: storage }).single('file')
//ROUTES WILL GO HERE
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.post('/api/uploadMultipleCsvFiles', function(req, res) {
console.log(req.body)
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.status(500).json(err)
} else if (err) {
return res.status(500).json(err)
}
return res.status(200).send(req.file)
})
})
app.listen(8081, () => console.log('Server started on port 8081'));