前后端对应

95 阅读2分钟

后端:

@RestController
@RequestMapping("articles")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CategoryService categoryService;
    
    @PostMapping("view/{id}")
    public Result findArticleById(@PathVariable("id") Long id) {
        return articleService.findArticleById(id);
    }
    @PostMapping("publish")
    public Result publish(@RequestBody ArticleParam articleParam){
        return articleService.publish(articleParam);
    }
    
    @GetMapping("comment")
    public Result getCommentsById(@RequestParam(value="id") String id){
        return categoryService.findAllDetail(id);
    }
    @GetMapping("detail/{id}")
    public Result categoryDetailById(@PathVariable("id") Long id){
        return categoryService.categoryDetailById(id);
    }
}

前端:

import axios from 'axios'

const service = axios.create({
  baseURL: "http://localhost:8888",
  timeout: 10000
})
export default service
import request from "@/request"

export function viewArticle(id) {
   return request({
      url: `/articles/view/${id}`,
      method: 'get'
   })
}
export function getCommentsByArticle(id) {
    return request({
        url: '/articles/comment',
        method: 'get',
        params:{
            "id":id
        }
    })
}
export function publish(ArticleParam) {
    return request({
        url: '/articles/publish',
        method: 'post',
        data: ArticleParam
    })
}
import {getArchives} from '@/api/article'
getArticles(this.innerPage).then((res) => {
 if (res.data.success) {
  ...
 } else {
  this.$message.error(res.data.msg);
 }
}).catch((err) => {
...
}).finally(() => {
...
})
  • @RequestParam(value="id")将url中的请求参数对应于接口函数的形参,以/path?id=2的形式,多个参数用&分隔,url传参在get,post中都可以用,对应前端axios的params部分,其会自动写入url。postman和axios都可以发带params的post请求

image.png

  • @PathVariable("id") url中请求参数以斜杠/path/1的形式,url中没有参数名,需要用@GetMapping("path/{id}")中参数占位来表明对应关系,前端axios的url部分需要自己写占位符参数/${id}
  • @RequestBody一般用于post请求的请求体中的参数,(get也可以,postman可以发带body的get请求,但axios的get请求不支持data部分),对应前端axios的data部分,默认是json格式传输,即Content-Type: application/json,而后端通过注解拿到的是实例对象 image.png Content-Type: multipart/form-data常用于图片上传、文件上传
let params = new FormData() 
params.append('file', this.file)

export function upload(ArticleParam) {
    return request({
        url: '/upload',
        method: 'post',
        data: params
    })
}

image.png

后端获取请求中的token:

@GetMapping("currentUser")
public Result currentUser(@RequestHeader("Authorization") String token){
    return sysUserService.getUserInfoByToken(token);
}

或者在拦截器里:

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        ...
    }
}

前端在请求中添加token

export function publishComment(comment,token) {
    return request({
        headers: {'Authorization': token},
        url: '/comments/create/change',
        method: 'post',
        data: comment
    })
}

或者拦截器里

service.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  if (store.state.token) {
    config.headers['Authorization'] = localStorage.token
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});