Axios发布request.body为空对象

编程入门 行业动态 更新时间:2024-10-22 14:44:46
本文介绍了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为空对象

本文发布于:2023-11-13 00:48:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582952.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   对象   Axios   request   body

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!