【问题标题】:Angular 2 and Laravel 5.3 API call error on POST Request is empty on controllerPOST 请求上的 Angular 2 和 Laravel 5.3 API 调用错误在控制器上为空
【发布时间】:2017-06-05 21:06:59
【问题描述】:

我正在使用 laravel 5.3 和 angular 2 中的客户端构建 API 服务。当我尝试将登录表单作为 JSON 数据提交时,登录控制器 (Laravel) 中的请求数据数组为空 []。我使用邮递员扩展测试了 API,它可以正常工作并返回 200 状态码。但是当 Angular 发送一个 POST 请求时,我 没有 在我的控制器上接收到任何东西。

Angular 2 Post 调用:

private authUrl = 'http://localhost:35656/api/authenticate';
var payload = JSON.stringify({ "email": email, "password": password });
    console.log(payload);
    return this.http.post(this.authUrl, payload, {
        //headers: headers
    }).map((response: Response) => {var status = response.json().status;});

Laravel 路线

header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS');
Route::post('authenticate', 'Auth\LoginController@authenticate');

Laravel 控制器

 /**
 * Return a JWT
 *
 * @return Response
 */
public function authenticate(Request $request)
{
    //$credentials = $request->only('email', 'password');
    $credentials = $request->all(); // IS EMPTY
    //$credentials = 'testing...';
    return response()->json(['status' => true, 'error' => $credentials]);
}

如果我在来自 Angular 的 POST 调用中执行此操作,那么它可以工作。

return this.http.post('http://localhost:35656/api/authenticate?email=xxx@eeeee.com&password=xxxxx', '')
        .map((response: Response) => {});

我的 Laravel Sever 是 http://localhost:35656,Angular 2 是 http://localhost:3000

我做错了什么?

【问题讨论】:

    标签: laravel angular laravel-5.3


    【解决方案1】:

    application/json 添加到您的标题中。

    【讨论】:

    • 根据请求添加标头后,我有这个错误Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.我坚持这个。有什么建议吗?
    • 我添加了这个header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Key'); 并修复了服务器问题。谢谢@vinit-sarvade ...它现在可以工作了!
    • 啊..是的。您需要将标头更新到您的服务器上以接受正在传入的新标头。通常如果 content-typeAccept 标头不存在,则数据将传递到您需要阅读的 PHP 正文中它通过 PHP 输入流php://input。但不建议这样做。
    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多