POST请求在Phoenix中转向200个选项但未发送以下POST

时间:2017-06-10 04:40:32

标签: angular cors elixir phoenix-framework

我正在使用Angular 2和Phoenix,我正在尝试向Phoenix发送POST请求。我有以下代码:

endpoint.ex

plug Corsica, origins: "http://localhost", allow_headers: ["content-type"]

在我的前端我有

@Injectable()
export class RegisterService {

    public headers: Headers;

    constructor(private _http: Http) {
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
    }

    createUser(): Observable<Response> {
        return this._http.post(
            'http://localhost:4000/v1/users', 
            JSON.stringify({
                firstName: 'lll',
                lastName: 'xxxxx',
                email: 'dddd@gmail.com',
                password: 'test123'
            }), 
            {headers: this.headers}
        );
    }
}

这是组件代码

createUser(): void {
    this._registerService.createUser().subscribe();
}

我得到200 OK OPTIONS但它从不发送POST请求。

常规

Request URL:http://localhost:4000/v1/users
Request Method:OPTIONS
Status Code:200 OK
Remote Address:127.0.0.1:4000
Referrer Policy:no-referrer-when-downgrade

响应标头

cache-control:max-age=0, private, must-revalidate
content-length:0
date:Sat, 10 Jun 2017 04:29:50 GMT
server:Cowboy
x-request-id:hfm969svbqv9oa2jatn5ri641srsht3s

请求标头

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:4000
Origin:http://localhost:4200
Referer:http://localhost:4200/signup

我的凤凰日志只是说

[info] OPTIONS /v1/users
[info] Sent 200 in 31µs

不确定我做错了什么。我确实稍微修改了我的router.ex ...不确定它是否会有所不同但是这里是

defmodule Api.Router do
  use Api.Web, :router

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", Api do
    pipe_through :api

    resources "/organizations", OrganizationController
  end

  scope "/v1", Api.V1, as: :v1 do
    pipe_through :api

    resources "/users", UserController, only: [:create, :show, :update]
  end
end

2 个答案:

答案 0 :(得分:1)

您需要配置http://localhost:4000/v1/users路由以发送包含Access-Control-Allow-Origin响应标头的响应,并且还包含Access-Control-Allow-Headers响应标头,其中包含字符串&#34; {{1 }}&#34;在值中,以及Content-Type响应标头中包含字符串Access-Control-Allow-Methods

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS详细解释。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests解释了浏览器发送POST请求的原因,以及浏览器需要的响应。

  

我得到200 OK OPTIONS但它从不发送POST请求。

那是因为如果OPTIONS响应中不包含OPTIONS标题,Access-Control-Allow-OriginAccess-Control-Allow-Headers标题包含上述值,那么浏览器就会停在那里并且永远不会发送Access-Control-Allow-Methods

答案 1 :(得分:1)

origins值与origin标头完全匹配。在您仅允许http://localhost:4200时,您的请求是发送原始值http://localhost。如果您要允许来自origins的请求,则需要将http://localhost:4200更改为http://localhost:4200

plug Corsica, origins: "http://localhost:4200", allow_headers: ["content-type"]