1、vue-cli创建的工程 config/index.js

修改dev下的proxyTable:

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/api': {
            target: 'http://localhost:9000', // 数据接口
            changeOrigin: true, // 跨域
            secure: false,
            pathRewrite: {
                '^/api': ''
            }
        }
    },

2、发起请求时:

import axios from 'axios'
import qs from 'qs'

axios.post('/api/user/login', qs.stringify({
    username: 'admin',
    password: '123456'
})).then(function (response) {
    console.log(response)
}).catch(function (error) {
    console.log(error)
})

关于使用qs 的说明:

来自官方的解析(https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

By default, axios serializes JavaScript objects to JSON

说明,默认是序列化为json


Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

Browser

In a browser, you can use the URLSearchParams API as follows:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

Note that URLSearchParams is not supported by all browsers (see
caniuse.com), but there is a polyfill available (make sure to polyfill
the global environment).

Alternatively, you can encode data using the qs library:

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

Or in another way (ES6),

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

Node.js

In node.js, you can use the querystring module as follows:

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

You can also use the qs library.


大意是:

要想使用 application/x-www-form-urlencoded 格式编码数据,可以有以下几种方式:

在浏览器:

可以使用 URLSearchParams

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

注意,URLSearchParams不是所有浏览器都兼容的。可以通过polyfill
做兼容

除了可以使用URLSearchParams,还可以使用qs库来编码数据

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

或者使用ES6的写法:

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

在Node.js环境

可以使用 querystring模块

const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

同样也可以使用qs

Logo

前往低代码交流专区

更多推荐