首页 > 解决方案 > Angular 7 - http 帖子 - 标题内没有发送 PAYLOAD

问题描述

我刚刚创建了一个 Angular 7 项目

我尝试发送带有一些数据的帖子,标题部分没有设置任何内容

所以在服务器端我只调用了 php 脚本,$_POST 数组中没有任何内容

此代码在 angular 5 中工作正常,我应该在 chrome 中看到标题日志中的数据

    createPostOptions() {
        let headers = new Headers({
            'Content-Type': 'application/json',
        });

        let options = new RequestOptions({ headers: headers, withCredentials: true });
        return options;
    }

    getParts(): Observable<any> 
    {
        return this.http.post('http://localhost/site/data.php',{command:'getParts'}, this.createPostOptions())
            .pipe(map((response: Response) => {
                return this.processData(response,this.router);
            }));
    }

php代码:

function cors()
{
    header("HTTP/1.1 " . "200" . " " . "OK");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");    
    header('Access-Control-Allow-Headers: Accept, Content-Type, Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Methods, X-Requested-With, X-API-KEY, X-Auth-Token, X-Requested-With, Authorization, Content-Range, Content-Disposition, Origin, Access-Control-Request-Method');
    header('Access-Control-Max-Age: 86400');
    header('Access-Control-Allow-Origin: '."http://localhost");
    header('Access-Control-Allow-Credentials: true');   
}

//-----------------------------------

if($_SERVER['REQUEST_METHOD']=="OPTIONS")
{
    cors();
}
else
{
    ...
}

在此处输入图像描述 我应该看到这样的东西

在此处输入图像描述 任何帮助表示赞赏

标签: phpangularpostangular7

解决方案


由于您在正文中发送 json,但不是作为 post 参数,因此您需要类似

$jsonInput = file_get_contents('php://input');
$obj = json_decode($jsonInput);
$command = $obj->command;

推荐阅读