Axios posting params not read by $_POST

前端 未结 5 828
旧时难觅i
旧时难觅i 2020-11-28 09:25

So I have this code:

axios({
    method: \'post\',
    url,
    headers: { \'Content-Type\': \'application/x-www-form-urlencoded\' },
    data: {
        jso         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 09:39

    Just wanted to share my insights, I was facing a similar problem and solved it by the following code set

    JS

    const instructions_str = {
      login: {
        "type": "devTool",
        "method": "devTool_login",
        "data": {
            "username": "test",
            "password": "Test@the9" 
        }
      },
      tables: {
        "type": "devTool",
        "method": "devTool_get_all_tables",
        "data": ""
      }
    };
    
    const body = {
        firstName: 'Fred',
        lastName: 'Flintstone',
        name: "John",
        time: "2pm",
        instructions : JSON.stringify(instructions_str)  
    };
    
    function decodeData(data) {
      const serializedData = []
    
      for (const k in data) {
        if (data[k]) {
          serializedData.push(`${k}=${encodeURIComponent(data[k])}`)
        }
      }
    
      return serializedData.join('&')
    };
    
    const body2 = decodeData(body);
    
    axios.post('URL', body2)
      .then(response => {
        console.log("contextApi got it", response);
      }).catch(error => {
          console.log("contextApi error.response", error.response);
      });
    

    PHP

    // set content return type
    header('Content-Type: application/json');
    
    // Setting up some server access controls to allow people to get information
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Methods:  POST, GET');
    
    // This way I can check and see what I sent
    $postVars_array = $_POST ?? parse_str(file_get_contents("php://input"),$postVars_array) ?? [];
    echo json_encode($postVars_array);
    

    I also found this github page very helpful https://github.com/axios/axios/issues/1195

提交回复
热议问题