【问题标题】:Nelmio_cors : error 400 when doing a POST to APINelmio_cors:对 API 进行 POST 时出现错误 400
【发布时间】:2018-09-27 11:51:07
【问题描述】:

这是我的问题。我在 Angular 5 上有一个前端网站,在 Symfony 3.4 上有一个后端 API。 我正在使用 FOSRestBundle 发出我的 API 请求。当我尝试向我的 API 发出 POST 请求时,出现错误:“无法加载 http://127.0.0.1:8000/api/pro/login:预检响应具有无效的 HTTP 状态代码 400。”

这是我的不同代码:

登录控制器.php:

<?php

namespace ProBundle\Controller;

use FOS\RestBundle\Controller\Annotations as Rest;
use Proxies\__CG__\ProBundle\Entity\Utilisateur;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class LoginController extends Controller
{
    /**
     * @Rest\Post(
     *      path = "/api/pro/login",
     *      name = "dropnride_pro_login"
     * )
     * @Rest\View
     * @ParamConverter("utilisateur", converter="fos_rest.request_body")
     */
    public function loginAction(Utilisateur $utilisateur)
    {
        $response = new Response($utilisateur->loginToString());

        return $response;
    }
}

login.component.ts:

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { LoginService } from '../services/login.service';

@Component({
  selector: 'dropnride-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [LoginService]
})
export class LoginComponent {

  constructor(private _loginService: LoginService) { }

  onSubmit(form: NgForm) {
    const email = form.value['email'];
    const password = form.value['password'];
    this.askLogin(email, password);
  }

  askLogin(email: string, motDePasse: string) {
    const userData = {
      email: '',
      motDePasse: '',
    }

    userData.email = email;
    userData.motDePasse = motDePasse;

    // Contact de l'API
    this._loginService.getLoginData(userData);

  }

}

login.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

const loginUrl = "http://127.0.0.1:8000/api/pro/login";

@Injectable()
export class LoginService {

  constructor(private http: HttpClient) {
   }

   getLoginData(userData) {

    const headers = new HttpHeaders({
       'Content-Type': 'application/json'
    });

     console.log(userData);
     return this.http.post(loginUrl, userData, {headers: headers}).subscribe(data => {
       console.log(data);
     });

   }

}

我的 API 调用与 Postman 配合得很好: API call through Postman

我已经在我的 config.yml 中安装并配置了 NelmioCorsBundle:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: ['*']
        allow_headers: ['*']
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['^http://localhost:[0-9]+']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: ['^api\.']

对于类似问题,我几乎尝试了所有其他 stackoverflow 的成员提案,但我找不到适合我的解决方案...您有什么想法可以帮助我解决我的问题吗?提前非常感谢:)

【问题讨论】:

  • 你在哪里/如何配置 cors?
  • 我编辑了我的帖子,我在 config.yml 中使用 NelmioBundle 配置了 CORS(我也忘了谈论它;))
  • 为什么要在服务中订阅 return

标签: api symfony post cors


【解决方案1】:

尝试将Content-Type 也设置为允许的标题

allow_headers: ['X-Custom-Auth', 'Content-Type]

并允许“OPTIONS”(不确定是否真的需要)

allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']

【讨论】:

  • 现在效果更好!谢谢!
猜你喜欢
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多