isAxiosError.js:10 POST http://localhost/api/management/book/create 400

来源:4-4 实现新增图书功能

困一

2021-12-18 22:58:23

相关截图:

https://img.mukewang.com/climg/61bdf6c109ca559d13230805.jpg

相关代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书管理</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" type="text/css" href="/assets/element-plus/index.css">
    <!-- 引入组件库 -->
    <script src="/assets/vue/vue.global.js"></script>
    <script src="/assets/element-plus/index.full.js"></script>
    <script src="/assets/axios/axios.js"></script>
    <script src="/assets/wang-editor/wangEditor.min.js"></script>

    <style>

        .info .el-col, .info .el-select, .info .el-input {
            padding-top: 5px;
            padding-bottom: 5px;
        }
    </style>
</head>
<body>
<div id="app">
    <h2>图书管理</h2>
    <!-- 新增图书按钮 -->
    <el-button type="primary" @click="createBook">新增图书</el-button>
    <!-- 数据表 -->
    <el-table
            ref="singleTable"
            :data="tableData"
            highlight-current-row
            style="width: 100%">
        <el-table-column
                property="categoryName"
                label="分类"
                width="100">
        </el-table-column>
        <el-table-column
                property="bookName"
                label="书名"
                width="300">
        </el-table-column>
        <el-table-column
                property="subTitle"
                label="子标题"
                width="300">
        </el-table-column>
        <el-table-column
                property="author"
                label="作者"
                width="300">
        </el-table-column>
        <el-table-column
                label="操作"
                width="100">
            <template #default="scope">
                <el-button type="text" size="small" @click="onEdit(scope.row)">修改</el-button>
                <el-button type="text" size="small" @click="onDelete(scope.row)">删除</el-button>

            </template>
        </el-table-column>

    </el-table>
    <!-- 分页组件 -->
    <el-pagination
            background
            layout="prev, pager, next"
            :total="count"
            :current-page="page"
            @current-change="changePage">
    </el-pagination>
    <!-- 新增/修改图书表单 -->
    <el-dialog :title="dialogTitle" v-model="dialogFormVisible" width="800px" top="5vh" center>
        <div class="info">
            <el-form :model="form" ref="bookForm" :rules="rules">
                <!-- 类别下拉框 -->
                <el-form-item prop="category" label-width="0px">
                    <el-select v-model="form.categoryId" placeholder="请选择类型" style="width: 100%">
                        <el-option label="前端" value="1"></el-option>
                        <el-option label="后端" value="2"></el-option>
                        <el-option label="测试" value="3"></el-option>
                        <el-option label="产品" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 书名 -->
                <el-form-item prop="bookName" label-width="0px">
                    <el-input v-model="form.bookName" placeholder="请输入书名" autocomplete="off"></el-input>
                </el-form-item>
                <!-- 子标题 -->
                <el-form-item prop="subTitle" label-width="0px">
                    <el-input v-model="form.subTitle" placeholder="请输入子标题" autocomplete="off"></el-input>
                </el-form-item>
                <!-- 作者 -->
                <el-form-item prop="author" label-width="0px">
                    <el-input v-model="form.author" placeholder="请输入作者" autocomplete="off"></el-input>
                </el-form-item>
                <!-- wangEditor容器 -->
                <div ref="editor" style="width: 100%"></div>
            </el-form>
            <span class="dialog-footer">
                <!-- 提交按钮 -->
              <el-button type="primary" v-on:click="onSubmit('bookForm')" style="width: 100%">确认提交</el-button>
            </span>
        </div>
    </el-dialog>
</div>

<script>
    let editor;
    const Main = {
        data() {
            return {
                dialogFormVisible: true //控制表单是否显示
                , dialogModel: "create" //表单提交模式 create-新增,update-修改
                , dialogTitle: "" //表单标题
                , form: { //表单数据
                    categoryId: "" //分类编号
                    , bookName: "" //书名
                    , subTitle: ""//子标题
                    , author: "" //作者
                    , description: "" //描述
                }
                , formLabelWidth: '120px' //表单文本宽度
                , tableData: [{}] //图书分页数据
                , count: 0 //记录总数
                , page: 1 //当前页码
                , pageCount : 0 //总页数
                , rules: { //校验规则
                    bookName: [
                        {required: true, message: '请输入书名', trigger: 'blur'}
                    ],
                    subTitle: [
                        {required: true, message: '请输入子标题', trigger: 'blur'}
                    ],
                    author: [
                        {required: true, message: '请输入作者', trigger: 'blur'}
                    ]
                }
            }
        }
        , methods: {
            //显示新增/修改图书对话框
            //model : create-新增图书 ,update-更新图书
            //data : 当模式为update时,代表表单原始数据
            showDialog(model, data) {
                this.dialogModel = model;
                if (model == "create") {
                    this.dialogTitle = "新增图书";
                    this.form.categoryId = "1";
                    this.form.bookName = "";
                    this.form.subTitle = "";
                    this.form.author = "";
                    this.form.description = "";
                    this.dialogFormVisible = true;
                } else if (model == "update") {
                    if (data != null) {
                        this.dialogTitle = "更新图书";
                        this.form = data;
                        this.form.categoryId = this.form.categoryId.toString();
                        this.dialogFormVisible = true;
                    }
                }
                //实例化wangEditor富文本编辑器
                editor = new wangEditor(this.$refs.editor);
                //设置上传图片的地址
                editor.customConfig.uploadImgServer = '/api/management/book/upload';//设置图片上传地址
                //默认上传时使用的参数名
                editor.customConfig.uploadFileName = 'img';//设置图片上传参数
                editor.create();//创建wangEditor
                //设置初始内容
                editor.txt.html(this.form.description);
            }
            , createBook() { //点击新增按钮,显示"新增图书"表单
                this.showDialog("create");
            }
            , onEdit : function(row){
                if (row != null) {
                    //点击修改按钮,显示"修改图书"表单
                    //row代表当前行数据
                    this.showDialog("update", row);
                }
            }
            , onDelete: function(row){
                const objApp = this;
                this.$confirm("确定要删除[" + row.bookName + "]吗?", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "warning"
                }).then(() => {
                    //处理删除操作
                });
            }
            , onSubmit: function (formName) {
                const objApp = this;
                const formData = this.form;
                this.$refs[formName].validate(function (valid) {
                    if (valid) {
                        const description = editor.txt.html();
                        const params = new URLSearchParams();
                        params.append("bookId", objApp.form.bookId);
                        params.append("bookName", objApp.form.bookName);
                        params.append("subTitle", objApp.form.subTitle);
                        params.append("description", description);
                        params.append("author", objApp.form.author);
                        params.append("categoryId", objApp.form.categoryId);
                        console.info("++++++++++++++++++");
                        console.info(params);
                        axios.post("/api/management/book/" + objApp.dialogModel,params)
                            .then(function(response){
                                const json = response.data;
                                if(json.code == "0"){
                                    ElementPlus.ElMessage.success({
                                        message : "数据处理成功",
                                        type : "success"
                                    })
                                    objApp.dialogFormVisible = false;
                                    if(objApp.dialogModel == "create"){
                                        objApp.changePage(objApp.pageCount);
                                    }else if(objApp.dialogModel == "update"){
                                        objApp.changePage(objApp.page);
                                    }
                                }else{
                                    console.error(json);
                                    ElementPlus.ElMessage.error({
                                        message : json.message,
                                        type : "error"
                                    })
                                }
                            })
                    }
                });
            }
            , changePage(page) {
                //显示第几页数据
                const objApp=this;
                axios.get("/api/management/book/list?page="+page)
                .then(function (response) {
                    const json=response.data;
                    if(json.code=="0"){
                        const bookList=json.data.list;
                        objApp.tableData.splice(0,objApp.tableData.length);
                        bookList.forEach(function (item){
                            objApp.tableData.push(item);
                        })
                        objApp.count=json.data.count;
                        objApp.page=json.data.page;
                        if(objApp.count % 10 == 0){
                            objApp.pageCount=Math.trunc(json.data.count/10);
                        }else{
                            objApp.pageCount=Math.trunc(json.data.count/10+1);
                        }
                    }else{
                        console.error(json);
                    }
                })
            }

        }
        , mounted() {
            this.dialogFormVisible = false;
            const objApp = this;
            this.changePage(1);
        }
    };
    const app = Vue.createApp(Main);
    app.use(ElementPlus);
    app.mount("#app")
</script>

</body>
</html>
package com.ssm.controller.mangement;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ssm.entity.Book;
import com.ssm.service.BookService;
import com.ssm.utils.ResponseUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/management/book")
public class MBookController {
   @Resource
   private BookService bookService;

   @GetMapping("/list")
   public ResponseUtils list(Integer page,Integer rows){
      ResponseUtils resp = new ResponseUtils();
      if(page==null){
         page=1;
      };
      if(rows==null){
         rows=10;
      };

      try{
         IPage mapIPage = bookService.selectBookMap(page, rows);
         resp=new ResponseUtils().put("list",mapIPage.getRecords()).put("count",mapIPage.getTotal());
      }catch (Exception e){
         e.printStackTrace();
         resp = new ResponseUtils(e.getClass().getSimpleName(),e.getMessage());
      }
      return resp;
   }

   @PostMapping("/upload")
   public Map upload(@RequestParam("img")MultipartFile file, HttpServletRequest request) throws IOException {
      //得到上传文件目录
      String uploadPath=request.getServletContext().getResource("/").getPath()+"/upload/";
      SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
      String fileName=sdf.format(new Date());
      //获取文件名后缀
      String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
      file.transferTo(new File(uploadPath+fileName+suffix));
      Map result=new LinkedHashMap();
      result.put("errno",0);
      result.put("data",new String[]{"/upload/"+fileName+suffix});
      return result;
   }
   @PostMapping("create")
   public ResponseUtils createBook(Book book){
      ResponseUtils resp;
      //<img src="..."/> <h1>....</h1>
      try {
         System.out.println(book.getDescription());
         Document doc = Jsoup.parse(book.getDescription());
         Elements elements = doc.select("img");
         if (elements.size() == 0) {
            resp = new ResponseUtils("ImageNotFoundError", "图书描述未包含封面图片");
            return resp;
         }
         String cover = elements.first().attr("src");
         book.setCover(cover);
         book.setEvaluationScore(0f);
         book.setEvaluationQuantity(0);
         Book b = bookService.createBook(book);
         resp = new ResponseUtils().put("book",b);
      }catch (Exception e){
         e.printStackTrace();
         resp = new ResponseUtils(e.getClass().getSimpleName(), e.getMessage());
      }
      return resp;
   }

}

问题描述:

无法通过axios访问http://localhost/api/management/book/create页面,提示400错误

写回答

2回答

慕瓜4328470

2022-06-29

同学,这个问题你解决了吗,我也遇到了这个问题
1
huperdogso
hp>你出现这个问题大概率是把update这个功能的源码也复制了,你把第一个请求参数bookid去了试试

h022-07-29
共1条回复

好帮手慕小尤

2021-12-19

同学你好,出现400表示这个请求是无效的,并没有进入后台服务器(控制器)里。可能是前端提交的字段名称或者字段类型和后台的实体类不一样。建议同学查看请求中的参数与book类中属性名称与类型是否相符。

祝学习愉快!

0

0 学习 · 9886 问题

查看课程

相似问题

回答 1

回答 1

回答 1