Skip to content

Commit

Permalink
* [html5] add content-type for post body
Browse files Browse the repository at this point in the history
  • Loading branch information
MrRaindrop committed Jun 30, 2016
1 parent 412a6e5 commit ea43f44
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
33 changes: 33 additions & 0 deletions html5/browser/api/stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ require('httpurl')
let jsonpCnt = 0
const ERROR_STATE = -1

const TYPE_JSON = 'application/json;charset=UTF-8'
const TYPE_FORM = 'application/x-www-form-urlencoded'

const REG_FORM = /^(?:[^&=]+=[^&=]+)(?:&[^&=]+=[^&=]+)*$/

function _jsonp (config, callback, progressCallback) {
const cbName = 'jsonp_' + (++jsonpCnt)
let url
Expand Down Expand Up @@ -54,6 +59,11 @@ function _xhr (config, callback, progressCallback) {
xhr.responseType = config.type
xhr.open(config.method, config.url, true)

const headers = config.headers || {}
for (const k in headers) {
xhr.setRequestHeader(k, headers[k])
}

xhr.onload = function (res) {
callback({
status: xhr.status,
Expand Down Expand Up @@ -109,6 +119,7 @@ const stream = {

/**
* sendHttp
* @deprecated
* Note: This API is deprecated. Please use stream.fetch instead.
* send a http request through XHR.
* @deprecated
Expand Down Expand Up @@ -220,6 +231,28 @@ const stream = {
+ typeOptions + '.')
}

// validate options.headers
config.headers = config.headers || {}
if (!utils.isPlainObject(config.headers)) {
return logger.error('options.headers should be a plain object')
}

// validate options.body
const body = config.body
if (!config.headers['Content-Type'] && body) {
if (utils.isPlainObject(body)) {
// is a json data
try {
config.body = JSON.stringify(body)
config.headers['Content-Type'] = TYPE_JSON
} catch (e) {}
} else if (utils.getType(body) === 'string' && body.match(REG_FORM)) {
// is form-data
config.body = encodeURI(body)
config.headers['Content-Type'] = TYPE_FORM
}
}

const _callArgs = [config, function (res) {
sender.performCallback(callbackId, res)
}]
Expand Down
6 changes: 6 additions & 0 deletions html5/browser/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ function isArray (arr) {
: (Object.prototype.toString.call(arr) === '[object Array]')
}

function isPlainObject (obj) {
return Object.prototype.toString.call(obj)
.slice(8, -1).toLowerCase() === 'object'
}

function getType (obj) {
return Object.prototype.toString.call(obj)
.slice(8, -1).toLowerCase()
Expand Down Expand Up @@ -147,6 +152,7 @@ function loopArray (arr, num, direction) {
module.exports = {
extend: extend,
isArray: isArray,
isPlainObject: isPlainObject,
getType: getType,
appendStyle: appendStyle,
getUniqueFromArray: getUniqueFromArray,
Expand Down

0 comments on commit ea43f44

Please sign in to comment.