$_POST 未读取 Axios 发布参数 [英] Axios posting params not read by $_POST

查看:28
本文介绍了$_POST 未读取 Axios 发布参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个代码:

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

最初我有正常的 axios.post 但我改为这个,因为我认为这可能是标题问题.但是,我的 $_REQUEST$_POST 中仍然没有检测到任何内容.但是,它正在file_get_contents("php://input") 中接收数据.

Originally I had the normal axios.post but I changed to this because I thought it might have been a header problem. However I am still detecting nothing in my $_REQUEST nor $_POST. However, it is receiving data in file_get_contents("php://input").

知道出了什么问题吗?

编辑

好吧,我想我知道出了什么问题.它将它作为一个 json 对象发布,所以它只能在 php://input 中读取.如何在 axios 中将其更改为普通字符串?

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. How do I change it to a normal string in axios?

推荐答案

来自 文档(我没有在引用的材料中保留链接):

From the documentation (I haven't preserved links in the quoted material):

默认情况下,axios 将 JavaScript 对象序列化为 JSON.

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON.

PHP 不支持 JSON 作为填充 $_POST 的数据格式.

PHP doesn't support JSON as a data format for populating $_POST.

它只支持机器可处理的格式 HTML 表单原生支持:

It only supports the machine-processable formats natively supported by HTML forms:

  • application/x-www-form-urlencoded
  • multipart/form-data

要以 application/x-www-form-urlencoded 格式发送数据,您可以使用以下选项之一.

To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

在浏览器中,您可以按如下方式使用 URLSearchParams API:

In a browser, you can use the URLSearchParams API as follows:

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

请注意,并非所有浏览器都支持 URLSearchParams,但有是一个 polyfill 可用(确保 polyfill 全局环境).

Note that URLSearchParams is not supported by all browsers, but there is a polyfill available (make sure to polyfill the global environment).

或者,您可以使用 qs 库对数据进行编码:

Alternatively, you can encode data using the qs library:

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

或者您可以自定义您的 PHP,以便它可以根据另一个问题的 this answer 处理 JSON.

Or you could customise your PHP so it can handle JSON as per this answer on another question.

这篇关于$_POST 未读取 Axios 发布参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆