Uniapp~动态修改 请求头的content-type 的值

1、创建request全局配置文件

在uniapp官网有这样一段话:

  • header默认的请求时 header['content-type'] 为 application/json
  • 对于 POST 方法且 header['content-type'] 为 application/json 的数据,会进行 JSON 序列化。
  • 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据,会将数据转换为 query string。

在全局配置文件中设置 请求拦截,通过拦截到的 自定义接口传参  判断是否修改header里面的content-type传参形式;

module.exports = (vm) => {
	// 初始化请求配置 
	
	// 设置跨域问题
	// #ifdef H5
	// 此为自定义配置参数,具体参数见上方说明
	uni.$u.http.setConfig({
		baseUrl: 'api',
		loadingText: '努力加载中~',
		loadingTime: 800,
		// ......
	});
	// #endif
 
// #ifndef H5
	// 此为自定义配置参数,具体参数见上方说明
	uni.$u.http.setConfig({
		baseUrl: 'http://192.168.xx.xx:xxxxx',
		loadingText: '努力加载中~',
		loadingTime: 800,
		// ......
	});
	// #endif 

	// 请求拦截
	uni.$u.http.interceptor.request = (config) => {  

    //通过 CONTENTTYPE 自定义的请求参数来判断的 是requestBody传参还是普通的query传参请求

		config.header['Content-Type'] =  config.header.CONTENTTYPE || 'application/json'

		return config
	}, config => { // 可使用async await 做异步操作
		return Promise.reject(config)
	}


}

在main.js中使用

import App from './App'
App.mpType = 'app'
const app = new Vue({
	...App
}) 
 
// 引入请求封装,将app参数传递到配置中
require('@/config/request.js')(app)

2、请求得api封装

const http = uni.$u.http

//通过自定义的 CONTENTTYPE 来修改是 query 传参模式
export const httpCustom= (params = {}) => http.post('url', params, {
	'CONTENTTYPE': 'application/x-www-form-urlencoded'
})


//这个是是 requestBody 传参模式 不需要传 CONTENTTYPE 
export const http= (data) => http.post('url', data)

uniapp官网~网络icon-default.png?t=M666https://uniapp.dcloud.io/api/request/request.html

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夢鑰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值