修改Content-Type 让request payload 转from data格式有问题?

async submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const res = await login({
            username: this.loginForm.username,
            password: hexMD5(this.loginForm.password)
          });
          console.log(res);
      });
    }
import {
  baseUrl
} from './env'

export default async (url = '', data = {}, type = 'GET', method = 'fetch') => {
  type = type.toUpperCase();
  url = baseUrl + url;

  if (type == 'GET') {
    let dataStr = ''; //数据拼接字符串
    Object.keys(data).forEach(key => {
      dataStr += key + '=' + data[key] + '&';
    })

    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
      url = url + '?' + dataStr;
    }
  }

  if (window.fetch && method == 'fetch') {
    let requestConfig = {
      credentials: 'include',
      method: type,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      mode: "cors",
      cache: "force-cache"
    }

    if (type == 'POST') {
      Object.defineProperty(requestConfig, 'body', {
        value: JSON.stringify(data)
      })
    }

    try {
      const response = await fetch(url, requestConfig);
      const responseJson = await response.json();
      return responseJson
    } catch (error) {
      throw new Error(error)
    }
  } else {
    return new Promise((resolve, reject) => {
      let requestObj;
      if (window.XMLHttpRequest) {
        requestObj = new XMLHttpRequest();
      } else {
        requestObj = new ActiveXObject;
      }

      let sendData = '';
      if (type == 'POST') {
        sendData = JSON.stringify(data);
      }

      requestObj.open(type, url, true);
      requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      requestObj.send(sendData);

      requestObj.onreadystatechange = () => {
        if (requestObj.readyState == 4) {
          if (requestObj.status == 200) {
            let obj = requestObj.response
            if (typeof obj !== 'object') {
              obj = JSON.parse(obj);
            }
            resolve(obj)
          } else {
            reject(requestObj)
          }
        }
      }
    })
  }
}

现在fetch是后台接收不到的格式

request payload

{"username":"circle","password":"9b6ddeba5b33e577c07c35d8505c6072"}: 

这是ajax POST这是后台能接收图中的格式

form data

username: circle
password: 9b6ddeba5b33e577c07c35d8505c6072

图片描述

请问怎么改造可以让后台POST时候收到收到参

阅读 5.8k
3 个回答
请问怎么改造可以让后台POST时候收到收到参

network看你前端本来就没问题,而问题就变成后端接收不到参数,那么后端可以处理什么content-type呢?(这是接口定义的问题,人家定义不接受form data你发过去有啥用)

一开始以为你是发送请求的截图,原来是后台给的成功实例。。
当然有问题,application/x-www-form-urlencoded发送数据的格式是a=b&c=d,而你发的是json字符串,你可以用qs模块转一下。

      if (type == 'POST') {
        sendData = JSON.stringify(data);
      }

      requestObj.open(type, url, true);
      requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      requestObj.send(sendData);

然后以后有关Network的问题,有什么不成功请截个图发出来才能看到你到底发送了什么。

我想想,应该要使用FormData函数:

let data=new FormData()
data.append('username','circle')
data.append('password','fffffffff')

然后直接使用data就行了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题