使用Angular HttpClient的POST请求不起作用

时间:2018-05-08 20:59:44

标签: php rest ionic-framework http-post angular-httpclient

我正在尝试从我的离子应用程序将用户数据发布到PHP RESTful API。我试着寻找解决方案但没有帮助。我创建了一个包含函数的提供程序,即" onSignup(signupForm)"在点击按钮时调用。

代码如下:

signup(username: string,email: string,password: string): void {

let headers = new HttpHeaders();
headers = headers.set("Content-Type","application/json; charset=UTF-8");
let body= {
  name:username, email:email, password:password
};

this.http.post('http://www.something.com/register', JSON.stringify(body), 
{headers: headers})
.subscribe(data => {
  console.log(data);
});
this.storage.set(this.HAS_LOGGED_IN, true);
this.setUsername(username);
this.events.publish('user:signup');
};

api的代码如下:

<?php
header("Access-Control-Allow-Origin:*");
header("Content-Type: application/json; charset=UTF-8");
require_once '../include/DbHandler.php';
require_once '../include/PassHash.php';
require '.././libs/Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

/**
* ----------- METHODS WITHOUT AUTHENTICATION ------------------------------- 
     --
     */
     /**
      * User Registration
      * url - /register
      * method - POST
      * params - name, email, password
      */
    $app->post('/register', function() use ($app) {
       file_put_contents("logs.txt","/register Route has been visited");

       // check for required params
       verifyRequiredParams(array('name', 'email', 'password'));

       $response = array();


       // reading post params
       $name = $app->request->post('name');
       $email = $app->request->post('email');
       $password = $app->request->post('password');

       // validating email address
       validateEmail($email);

       $db = new DbHandler();
       $res = $db->createUser($name, $email, $password);

       if ($res == USER_CREATED_SUCCESSFULLY) {
           $response["error"] = false;
           $response["message"] = "You are successfully registered";
       } else if ($res == USER_CREATE_FAILED) {
           $response["error"] = true;
           $response["message"] = "Oops! An error occurred while registereing";
       } else if ($res == USER_ALREADY_EXISTED) {
           $response["error"] = true;
           $response["message"] = "Sorry, this email already existed";
       }
       // echo json response
       echoRespnse(201, $response);
   });

我收到的错误是

  1. 无法加载资源:服务器响应状态为404(未找到)。

  2. 无法加载http://www.something.com/register:预检的响应包含无效的HTTP状态代码404

  3. 此API在Postman中运行良好,但在Chrome中运行应用时遇到了问题。

    我在API或POST调用期间是否缺少某些内容?

    请帮忙。在此先感谢。

    修改

    我添加了网络标签截图。这就是我在请求和响应标头中获得的内容。我猜这两个标题可能不匹配,但它肯定不会成为CORS问题,因为我可以在没有任何CORS问题的情况下进行GET调用。Network Tab Screenshot

    添加了包含错误的控制台选项卡屏幕截图:

    Console error

2 个答案:

答案 0 :(得分:1)

由于它是从Postman工作而不是你的应用程序,我会好好看看CORS。您需要在请求进入时设置标题,对于发布请求,Angular HttpClient将发送OPTIONS请求。

我不太多使用PHP,但也许这样的东西可以使用

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Content-Length: 0');
    header('Content-Type: application/json');
    die();
}

编辑:由于您使用的是Slim Framework,我假设您提供的代码。您可以根据Slim Framework v2 Docs(不确定您使用的是哪个版本)描述OPTIONS请求。

$app->options('/register', function ($app) {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Content-Length: 0');
    header('Content-Type: application/json');
    die();
});

或者您可以设置标题,如下所述 https://www.slimframework.com/docs/v2/response/headers.html

$app->response->headers->set('Access-Control-Allow-Origin', '*');
$app->response->headers->set('Access-Control-Allow-Methods', 'POST, OPTIONS');
$app->response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
$app->response->headers->set('Content-Type', 'application/json');

答案 1 :(得分:0)

尝试

header('Access-Control-Allow-Origin: *'); 
$dados = file_get_contents('php://input');

您将从角度请求中获取JSON ...