【问题标题】:Post method using PHP on Azure在 Azure 上使用 PHP 的发布方法
【发布时间】:2016-01-23 11:59:53
【问题描述】:

我直接从其他完美运行的地方复制并粘贴了这段代码相同的代码!有任何想法吗?

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}


$postdata = file_get_contents("php://input");
if (isset($postdata)) {
    $request = json_decode($postdata);
    $username = $request->username;

    if ($username != "") {
        echo "Server returns: " . $username;
    }
    else {
        echo "Empty username parameter!";
    }
}
else {
    echo "Not called properly with username parameter!";
}
?>

【问题讨论】:

  • 请粘贴 HTTP 请求和响应(如果有)日志 - 谢谢 - 和 HTTP 代码

标签: php angularjs http azure post


【解决方案1】:

默认情况下,当您在 PHP 中创建 Azure Web App 服务时,PHP 运行时没有名为 HTTP_ORIGIN 的变量,变量 REQUEST_METHOD 仅设置为 'GET。您可以在 Azure 上的 PHP 脚本中编写代码 phpinfo(); 来检查 Azure 上 PHP 运行时的配置。

所以前 2 个 IF 闭包中的代码永远不会运行。因此,如果您的 AngularJs 客户端与您的 PHP 服务器不在同一个域中(它们应该在一个 Azure Web App Service 中),当您的客户端请求 PHP 服务器时,它将引发 CORS 问题。

因此,您可以在 Azure 门户的应用设置中设置您的自定义 HTTP_ORIGIN,这将在您的应用启动时在 PHP 运行时中设置。

  • 登录Azure classic portal,进入管理您网站的页面标题。
  • 点击配置标签,向下滚动到应用设置部分
  • 为您的 AngularJs 客户端端点设置 HTTP_ORIGIN。例如。如果您的 AngularJs 客户端在本地运行,您应该将 HTTP_ORIGIN 设置为 localhost
  • 点击底部导航中的保存按钮,然后点击重新启动按钮以重新启动网站以加载您的自定义设置。

然后您可以在本地服务器上测试您的 AngularJs 应用程序:

$http({
    url: 'http://<your_web_site_na,e>.azurewebsites.net/<post_page>.php',
    method: "POST",
    data: { username: 'username', password: 'password' },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  })
  .success(function (data, status, headers, config) {
    console.log(data);
  })
  .error(function (data, status, headers, config) {
    $scope.status = status;
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多