简体   繁体   English

$_POST 未读取 Axios 发布参数

[英]Axios posting params not read by $_POST

So I have this code:所以我有这个代码:

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

Originally I had the normal axios.post but I changed to this because I thought it might have been a header problem.最初我有正常的axios.post但我改为这个,因为我认为这可能是标题问题。 However I am still detecting nothing in my $_REQUEST nor $_POST .但是,我仍然没有在$_REQUEST$_POST检测到任何内容。 However, it is receiving data in file_get_contents("php://input") .但是,它正在file_get_contents("php://input")接收数据。

Any idea what is wrong?知道出了什么问题吗?

Edit编辑

Okay I think I know what's wrong.好吧,我想我知道出了什么问题。 It's posting it as a json object so it can only be read in the php://input.它将它作为一个 json 对象发布,所以它只能在 php://input 中读取。 How do I change it to a normal string in axios?如何在 axios 中将其更改为普通字符串?

From the documentation (I haven't preserved links in the quoted material):文档(我没有在引用的材料中保留链接):

Using application/x-www-form-urlencoded format使用 application/x-www-form-urlencoded 格式

By default, axios serializes JavaScript objects to JSON.默认情况下,axios 将 JavaScript 对象序列化为 JSON。

PHP doesn't support JSON as a data format for populating $_POST . PHP 不支持 JSON 作为填充$_POST的数据格式。

It only supports the machine-processable formats natively supported by HTML forms :它仅支持HTML 表单本机支持的机器可处理格式:

  • application/x-www-form-urlencoded应用程序/x-www-form-urlencoded
  • multipart/form-data多部分/表单数据

To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.要改为以 application/x-www-form-urlencoded 格式发送数据,您可以使用以下选项之一。

Browser浏览器

In a browser, you can use the URLSearchParams API as follows:在浏览器中,您可以使用 URLSearchParams API,如下所示:

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

Note that URLSearchParams is not supported by all browsers, but there is a polyfill available (make sure to polyfill the global environment).请注意,并非所有浏览器都支持 URLSearchParams,但有一个可用的 polyfill(确保对全局环境进行 polyfill)。

Alternatively, you can encode data using the qs library:或者,您可以使用 qs 库对数据进行编码:

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

Or you could customise your PHP so it can handle JSON as per this answer on another question.或者您可以自定义您的 PHP,以便它可以根据另一个问题的这个答案处理 JSON。

var params = {
    data1: 'string',
}

axios.post(url, params).then(function(response) {
    //code here 
});

or或者

axios.post(url, {data1: 'string' }).then(function(response) {
    //code here 
});

api接口

$_POST = json_decode(file_get_contents("php://input"),true);
echo $_POST['data1'];

To make things easier and universal if you ever decided to switch between AJAX libraries or server languages.如果您决定在AJAX库或服务器语言之间切换,则使事情变得更容易和通用。 With axios use the native JS FormData .使用axios使用原生 JS FormData
If you have your data in an object, you can convert it to FormData like this:如果您在对象中有数据,则可以将其转换为FormData如下所示:

var myDataObj = {id:1, name:"blah blah"}
var formData = new FormData();


for (var key in myDataObj) {
    formData.append(key, myDataObj[key])
}

Then you send the data:然后你发送数据:

axios.post('/sub/process.php', formData, {
    params: { action: "update-user" },
    headers: { 'Content-Type': 'multipart/form-data' },
    baseURL: 'http://localhost',
}).then(data =>
    console.log(data)
).catch(err => {
    console.log(err)
    return null
})

Notice, you can also send some info using params in axios that you can retrieve using $_GET .请注意,您还可以使用axios中的params发送一些信息,您可以使用$_GET检索这些信息。 Also notice that I am using the baseURL in case you have different servers for the web page and your API endpoint.另请注意,我使用的是 baseURL,以防您为网页和 API 端点使用不同的服务器。
You need to understand also that before axios send the real request, it performs a preflight request.您还需要了解,在axios发送真正的请求之前,它会执行preflight请求。 A preflight request, is a mechanism in CORS by the browser to check if the resource destination is willing to accept the real request or not. 预检请求是浏览器在 CORS 中的一种机制,用于检查资源目的地是否愿意接受真正的请求。 Afterall, why would a request be sent when the target host is not willing to receive it anyway? 毕竟,当目标主机无论如何都不愿意接收时,为什么要发送请求?

You have to make sure that your server has the right headers for your axios request, otherwise the preflight request will detect the incompatibility and stop your request:您必须确保您的服务器具有适用于您的 axios 请求的正确标头,否则预检请求将检测到不兼容并停止您的请求:

//this is if you are using different different origins/servers in your localhost, * to be update with the right address when it comes to production
header('Access-Control-Allow-Origin: *');
//this is if you are specifying content-type in your axios request
header("Access-Control-Allow-Headers: Content-Type");

Now, you will able to access your sent data in the $_POST variable:现在,您将能够在$_POST变量中访问您发送的数据:

echo "<pre>";
print_r($_POST);
echo "</pre>";

Additionally, axios allows you to send data in different formats.此外,axios 允许您以不同格式发送数据。 you can send a json for example like this:你可以像这样发送一个json:

axios.post('/sub/process.php', { id: "1", name:"blablah" }, {
    params: { action: "update-item" },
    headers: { 'Content-Type': 'application/json' },
    baseURL: 'http://localhost',
}).then(data =>
    console.log(data)
).catch(err => {
    console.log(err)
    return null
})

In the PHP side, this can be accessed as follows:在PHP端,可以这样访问:

$data = json_decode(file_get_contents("php://input"),true);
echo "<pre>";
print_r($data);
echo "</pre>";

Using PHP std object使用 PHP std 对象

Using PHP std object structure to get the variables of the post.使用 PHP std 对象结构来获取 post 的变量。

On the client:在客户端:

axios.post(url, {id: 1 , Name:'My Name' }).then(function(response) {
    console.log(response.data);
});

On the server在服务器上

$obj = json_decode(file_get_contents('php://input'));   
$id = $obj->id;
$Name = $obj->Name;    

//test by returning the same values
$retObj=(object)["id"=>$id,"Name"=>$Name]
echo json_encode($retObj);

Both jQuery and Axios using same PHP file jQuery 和 Axios 使用相同的 PHP 文件

if you have a file receiving post both from axios and jquery you may use:如果您有一个从 axios 和 jquery 接收帖子的文件,您可以使用:

if($_SERVER['REQUEST_METHOD']==='POST' && empty($_POST)) {
   $_POST = json_decode(file_get_contents('php://input'),true); 
}

to convert the Axios json-serialized posts to the $_POST array将 Axios json 序列化的帖子转换为 $_POST 数组

You can use jQuery.param 您可以使用jQuery.param

postdata = $.param({param1: 'value1', param2:'value2'})

You can now use postdata has your post parameter 您现在可以使用postdata包含您的post参数

This code works on browser/node both today.此代码今天适用于浏览器/节点 I think this is more practical.我觉得这个更实用。 I tested this code on PHP8 using $_POST['param1'] and it worked.我使用$_POST['param1']在 PHP8 上测试了这段代码并且它工作正常。

function axqs(d){
    let p = new URLSearchParams();
    Object.keys(d).forEach(function(key){
        p.append(key, this[key]);
    }, d);
    return p
}

let data = {
  'param1': 'value1',
  'param2': 'value2',
}

let p = axqs(data)
axios.post('/foo', p)

Just wanted to share my insights, I was facing a similar problem and solved it by the following code set只是想分享我的见解,我遇到了类似的问题并通过以下代码集解决了它

JS 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 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我还发现这个 github 页面非常有用https://github.com/axios/axios/issues/1195

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM