gpt4 book ai didi

node.js - axios post request.body 为空对象

转载 作者:搜寻专家 更新时间:2023-10-31 22:21:50 25 4
gpt4 key购买 nike

我正在尝试从我的 react 中发布数据。后端 - express 。这是后端代码:

var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var mongoose = require("mongoose");
var expressSanitizer = require("express-sanitizer");

mongoose.connect("mongodb://localhost/blog-react");

//app config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
//must be after parser
app.use(expressSanitizer());
app.use(methodOverride("_method"));

//schema config
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
//it should be date. With default value now.
created: {
type: Date, default: Date.now
}
});

var Blog = mongoose.model("Blog", blogSchema);


function handle500(response, error){
console.log(error.stack);
response.status(500);
response.json({error: "error: internal server error"});
}

app.post("/api/blogs", function(request, response){
var blog = {
title: request.sanitize(request.body.title),
image: request.sanitize(request.body.image),
body: request.sanitize(request.body.body)
};
console.log(request.body);
Blog.create(blog, function(error, newBlog){
if(error){
console.log("inside post handler ERROR")
handle500(response, error);
}
else{
console.log("inside post handler OK")
response.json({status: "success"});
}
});
});

react 代码:

    var requestUrl = "/api/blogs";      
var blog = {
title: "a",
image: "b",
body: "c"
}
axios.post(requestUrl, blog)
.then(function(response){
console.log("success",response.data)
})
.catch(function(response){
console.log("error", response);
});

当我通过 axios 发布数据时 - request.body 始终是 {}但是,如果我通过常规形式发布数据 - 一切都是正确的 - request.body 包含所有预期数据。

我对 axios 做错了什么?

最佳答案

您缺少一个中间件,bodyParser.json() .将其添加到您的配置中。

mongoose.connect("mongodb://localhost/blog-react");

app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.json()); // <--- Here
app.use(bodyParser.urlencoded({extended: true}));

关于node.js - axios post request.body 为空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40859299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com