Javascript 无法使用fetch将react中的数据发布到nodejs
我使用fetch将数据从react端发布到nodejs(这两个节点都在本地主机上运行),所以我所做的是Javascript 无法使用fetch将react中的数据发布到nodejs,javascript,node.js,express,Javascript,Node.js,Express,我使用fetch将数据从react端发布到nodejs(这两个节点都在本地主机上运行),所以我所做的是 let formData = new FormData(); formData.append("agent_name", this.state.agentName); formData.append("agent_email", this.state.agentEmail); formData.append("agent
let formData = new FormData();
formData.append("agent_name", this.state.agentName);
formData.append("agent_email", this.state.agentEmail);
formData.append("agent_phone", this.state.agentPhone);
formData.append("agent_id", this.state.agentID);
formData.append("agent_password", this.state.agentPassword);
formData.append("state", this.state.selectedState);
formData.append("city", this.state.selectedCity);
formData.append("file", this.state.file);
formData.append("imageurl", this.state.imageUrl);
fetch("http://localhost:4000/add_delivery_agent", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((responsejson) => {
console.log(responsejson);
});
然后在服务器端我做到了
exports.addDeliveryAgent = async (req, res, next) => {
let data = req.body;
console.log(data);
}
};
但是console.log(data)总是给我空对象,我做错了什么
数据也通过axios发布,但我希望通过fetch
App.js配置是
const express = require("express");
const bodyparser = require("body-parser");
const app = express();
const mongoconnect = require("./utils/database").mongoconnect;
const path = require("path");
var cors = require("cors");
// const adminUserRoute = require("./routes/admin/user/user.js");
const adminDeliveryAgentRoute = require("./routes/admin/deliveryAgent/deliveryAgent");
const user = require("./routes/admin/user/user.js");
app.use(express.urlencoded());
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.use(cors());
app.use("/tfd/controlcenter/", express.static(path.join(__dirname, "/build")));
// app.use(adminUserRoute);
app.use(adminDeliveryAgentRoute);
app.use(user);
mongoconnect(() => {
app.listen(4000, () => {
console.log("running 4000");
});
});
尝试添加
内容类型
标题
fetch("http://localhost:4000/add_delivery_agent", {
method: "POST",
body: formData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
// or
// 'Content-Type': multipart/form-data
},
})
不要使用表单数据,而是使用普通对象,因为bodyparser不支持表单数据所使用的多部分/表单数据
formData={}
formData.agent_name=this.state.agentName;
formData.agent_email=this.state.agentEmail;
//..
formData.imageurl=this.state.imageUrl;
fetch("http://localhost:4000/add_delivery_agent", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((responsejson) => {
console.log(responsejson);
});
您是否在开始解析formdata时包含了
app.use(express.urlencoded())
@淘汰产生是的伴侣!!。我认为您需要multer
或nodejs模块来解析表单数据。您是否在后端代码中应用了cors设置?@VivekSingh yesi还想上传一个文件,这样我们可以用普通对象发送一个文件?看起来您发送的是图像url,还是文件对象?不管怎样,这里可能的最大文件大小是多少?我在这里发送一个文件对象,没有大小限制,我也在发送一个只有70kb的图像,那么普通对象在这里不会有用,试着使用一些bodyparser,比如