When using axios in Vue to send a post request, it may happen that the backend cannot receive the parameters.

When using axios in Vue to send a post request, it may happen that the backend cannot receive the parameters. The reason for this problem is that the request sent by axios by default is in json format, while the request received by the backend is in form format, which makes the backend unable to obtain the request parameters in json format. To solve this problem, you can set the request format to form format by setting the request header information of axios.

The following is a sample code for Vue to simply encapsulate axios and solve the problem that the backend of the post request cannot receive parameters:

  1. First install the axios and qs libraries:
npm install axios qs --save
  1. Create a new api folder in the src directory, and create a new http.js file:
import axios from 'axios'
import qs from 'qs'

axios.defaults.baseURL = 'http://localhost:3000' // 设置请求的基础url

//添加一个请求拦截器
axios.interceptors.request.use(function(config){
    
    
  //设置post请求的请求头部信息
  if(config.method=='post'){
    
    
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    config.data = qs.stringify(config.data);
  }
  return config;
},function(error){
    
    
  return Promise.reject(error);
});

export default axios //导出axios
  1. Create a new users.js file under the api folder as an example:
import axios from './http'

export function login (params) {
    
    
  return axios.post('/login', params)
}

export function getUserList () {
    
    
  return axios.get('/users')
}

export function addUser (params) {
    
    
  return axios.post('/users', params)
}

export function deleteUser (userId) {
    
    
  return axios.delete('/users/' + userId)
}

export function updateUser (userId, params) {
    
    
  return axios.put('/users/' + userId, params)
}

In this way, you need to import the users.js file under the api folder in Vue, and then call the corresponding function to send the request. For post requests, parameters need to be passed in as objects.

// 发送post请求示例
this.$api.login({
    
    
  username: 'admin',
  password: '123456'
}).then(response => {
    
    
  console.log(response)
}).catch(error => {
    
    
  console.log(error)
})

// 发送get请求示例
this.$api.getUserList().then(response => {
    
    
  console.log(response)
}).catch(error => {
    
    
  console.log(error)
})

After this setting, the post request can be sent normally, and the backend can also receive the parameters correctly.

Guess you like

Origin blog.csdn.net/weixin_46286150/article/details/129989696