The front-end and back-end projects use method: 'delete' to request an error: has been blocked by CORS policy: ...

1. Backend part

The background uses the @PostMapping annotation, which completes logical deletion through post requests.

    /**
     * 根据id删除
     */
    @ApiOperation(value="通过id删除",notes = "逻辑删除")
    @PostMapping("remove/{id}")
    public R removeById(@ApiParam(value = "xxx",required = true)@PathVariable  String id){
        System.out.println("进入删除方法");
        Boolean result=tsService.removeById(id);
        if(result){
            return R.ok().message("删除成功");
        }
        return  R.error().message("删除失败");
    }

2. Front-end part

The API used by the front-end part to communicate with the back-end uses method: 'delete'

    /**
     * 通过id删除信息
     * @param {*} id 
     */
     deleteTeacherById(id) {
        return request({
          url: `/admin/edu/teacher/remove/${id}`,
          method: 'delete',
      
        })
      } 

3. When performing logical deletion operations

The following error will occur, which looks very similar to a cross-domain error.

 translate:

Access to XMLHttpRequest at 'http:localhost: 9110adminedueacherremove15717511599017287' from origin 'http:localhost:9528' has been blocked by CORS policy: Response to preflight request failed access control check: No 'Access-Control-Allow-Origin' header exists on the requested resource

In fact, the way of requesting is different. 

Modification method one:

Modify the front-end code to change method: 'delete' to method: 'post', and then pass delete by passing parameters. This ensures that both the front-end and the back-end make post requests.

    /**
     * 通过id删除信息
     * @param {*} id 
     */
     deleteTeacherById(id) {
        return request({
          url: `/admin/edu/remove/${id}`,
          method: 'post',
          params:{
            method:'delete'
          }
        })
      }

 

Modification method two:

Change @PostMapping to @DeleteMapping on the backend

 This error often occurs because the request method is not corresponding, so you should be more careful! ! !

Guess you like

Origin blog.csdn.net/m0_56233309/article/details/126982691