我在将我的 API 与我的前端应用程序连接时遇到了一些问题。该 API 用于将 csv 文件的内容上传到 MongoDB 集合。为此,我制作了一个简单的表格,要求提供 csv 文件,但我不知道如何将此文件上传到我的 api 可以对其执行操作的服务器并将其存储在 Mongodb 中。
这是API的控制器文件:
var Stds = require('../models/stds')
var csv = require('csvtojson')
const importStds = async(req,res)=>{
try{
var stdsData = [];
csv()
.fromFile(req.file.path)
.then(async(response) => {
for(var x = 0; x < response.length; x++){
stdsData.push({
enNo: response[x].EnNo,
name: response[x].Name,
sec: response[x].Sec,
})
}
})
await Stds.insertMany(stdsData)
res.send({status:200, success: true, msg:'Imported'})
} catch(error) {
res.send({status:400, success: false, msg:error.message})
}
}
module.exports = importStds
这是它的路由文件:
var express = require('express')
const stds = express()
const multer = require('multer')
const path = require('path')
const bodyParser = require('body-parser')
stds.use(bodyParser.urlencoded({extended:true}))
stds.use(express.static(path.resolve(__dirname,'public')))
var storage = multer.diskStorage({
destination:(req,file,cb) => {
cb(null, './public/uploads')
},
filename:(req,file,cb) =>{
cb(null, file.originalname)
}
})
var upload = multer({storage:storage})
const stdsController = require('../controllers/stdsC')
stds.post('/importStds', function(req,res) {stdsController.importStds})
module.exports = stds;
这就是我在后端 index.js 文件中调用它的方式:
var stdsRoute = require('./routes/stdsR')
app.use('/', stdsRoute)
这是表格:
<div id="batchfield">
<label for="bfile">Upload Student Info:</label>
<input type="file" name="bfile" id="bfile" accept=".csv"></input>
<div className="button" onClick={() => subBatch({})}>Submit</div>
</div>
这是我尝试用来上传文件的功能。
const subBatch =() => {
const batch = document.getElementById("bfile")
const data = new FormData()
data.append("csv-file", batch)
axios.post("http://localhost:9002/stdsRoute", data)
.then(res => {
alert(res.data.message)
})
}
我是初学者,所以我真的不知道我在做什么,希望得到任何帮助
正如@JSEvgeny 所提到的,您的问题在于调用 API。
特别是这一行:
axios.post("http://localhost:9002/stdsRoute", data)
您的端点在此行中命名:
stds.post('/importStds', function(req,res) {stdsController.importStds})
这意味着前者应该切换为:
axios.post("http://localhost:9002/importStds", data)
为了正确调用 API 端点。