本文介绍了Axios发布request.body为空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从我的反应中发布数据.后端-快递.这是后端代码:
I am trying to post data from my react. Backend - express. Here is backend code:
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"}); } }); });反应代码:
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包含所有预期数据.
When I post data via axios - request.body is always {} But if I post data via regular form - all is correct - request.body contains all expected data.
axios我在做什么错?
What am I doing wrong with axios?
推荐答案您缺少一个中间件, bodyParser.json() .将其添加到您的配置中.
You are missing one middleware, bodyParser.json(). Add it to your configuration.
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}));更多推荐
Axios发布request.body为空对象
发布评论