【瑞模网】前端ajax请求接口,后端接口实际已经访问到了,数据库中已经插入数据成功。但是前端报404

正常情况下,前端报404错误是指没有找到接口。但是目前这种情况后端接口已经成功执行,但是前端依旧报错404。错误如下:

但是后端接口正常执行,数据库已经增加了一条记录

前端代码:

 this.$http.post("/shop/settledIn",para).then((res) => {
                                if(res.data.success){
                                    this.$message({
                                        message: '操作成功!',
                                        type: 'success'
                                    });
                                    //重置表单
                                    this.$refs['shopForm'].resetFields();
                                    //跳转登录页面
                                    this.$router.push({ path: '/login' });
                                }
                                else{
                                    this.$message({
                                        message: res.data.msg,
                                        type: 'error'
                                    });
                                }
                            });

后端代码:

package com.rk.pethome.controller;
import com.rk.pethome.domain.Shop;
import com.rk.pethome.service.IShopService;
import com.rk.pethome.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@Controller
@RequestMapping("/shop")
public class ShopController {
 
    @Autowired
    private IShopService shopService;
 
    /**
     * 店铺入驻
     * @param shop
     * @return
     */
    @PostMapping("/settledIn")
    public AjaxResult settledIn(@RequestBody Shop shop){
        try {
            shopService.settledIn(shop);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }
    }
}

找了很久才发现这个错误,刚开始以为是前端的错误,其实是后端接口的注解用错了,这里返回的是对象而不是视图, 应该使用的是@RestController注解而不是@Controller注解。

@Controller和@RestController区别:

@Controller 是视图解析器的,即Return返回的是视图,即jsp或者html页面的。

如果返回数据json、xml等,需要在对应的方法上加上@ResponseBody注解。

@RestController 是@Controller和@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面

猜你喜欢

转载自blog.csdn.net/rrmod/article/details/128905648