javascript 无法在 AngularJS 中的请求中指定标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19247725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:52:45  来源:igfitidea点击:

Can't specify headers in request in AngularJS

javascriptruby-on-railsangularjscross-domainangular-http

提问by zishe

I have 2 parts in my app - Angular frontend and rails server. And because it's different domains, requests doesn't work by default. There are a lot of staff about that, including stack, but it doesn't works for me.

我的应用程序中有 2 个部分 - Angular 前端和 Rails 服务器。因为它是不同的域,所以默认情况下请求不起作用。有很多工作人员,包括堆栈,但它对我不起作用。

This is my method in angular controller:

这是我在角度控制器中的方法:

$scope.test =->
  # transform = (data) ->
  #   $.param data

  $http.post('http://localhost:3000/session/create', 'token=some',
    headers:
      'Access-Control-Allow-Origin': 'http://localhost:9000',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
    # transformRequest: transform
  ).success (responseData) ->
    console.log(responseData)

I commented transform data, there is no difference in server response.

我评论了转换数据,服务器响应没有区别。

And I configured app (saw this in some post) like that:

我像这样配置了应用程序(在一些帖子中看到过):

.config ["$httpProvider", ($httpProvider) ->
  $httpProvider.defaults.useXDomain = true
  delete $httpProvider.defaults.headers.common["X-Requested-With"]
]

I guess that makes request not ajax like (but i'm not sure).

我想这使得请求不像 ajax 那样(但我不确定)。

But there is no headers in my request. They all in some field Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type:

但是我的请求中没有标题。他们都在某个领域Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type

    Request URL:http://localhost:3000/session/create
    Request Method:OPTIONS
    Status Code:404 Not Found

    Request Headers

    Accept:*/*
    Accept-Encoding:gzip,deflate,sdch
    Accept-Language:en-US,en;q=0.8,ru;q=0.6
    Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type
    Access-Control-Request-Method:POST
    Connection:keep-alive
    DNT:1
    Host:localhost:3000
    Origin:http://localhost:9000
    Referer:http://localhost:9000/
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.8 Safari/537.36

    Response Headers

    Content-Length:12365
    Content-Type:text/html; charset=utf-8
    X-Request-Id:2cf4b37b-eb47-432a-ab30-b802b3e33218
    X-Runtime:0.030128

Chrome console:

铬控制台:

OPTIONS http://localhost:3000/session/create 404 (Not Found) angular.js:6730
OPTIONS http://localhost:3000/session/create No 'Access-Control-Allow-Origin' header is     present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. angular.js:6730
XMLHttpRequest cannot load http://localhost:3000/session/create. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. localhost/:1

Other insignificant information: On the server:

其他无关紧要的信息: 在服务器上:

class ApplicationController < ActionController::Base
  before_filter :allow_cross_domain_access

  protected

  def allow_cross_domain_access
    headers['Access-Control-Allow-Origin'] = '*'# http://localhost:9000
    headers['Access-Control-Allow-Headers'] = 'GET, POST, PUT, DELETE'
    headers['Access-Control-Allow-Methods'] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(',')
    headers['Access-Control-Max-Age'] = '1728000'

  end
end

Routes is obvious post "session/create". And session controller:

路线很明显post "session/create"。和会话控制器:

class SessionController < ApplicationController
  respond_to :json, :html, :js

  def create
    respond_with "logged in"
    # render nothing: true
  end
end

I use latest version of angular 1.2.0.rc-2. this is my project on github

我使用最新版本的 angular 1.2.0.rc-2。这是我在 github 上的项目

采纳答案by Thomas

You mix up the request and response headers in your example.

您在示例中混淆了请求和响应标头。

When doing a cross domain request (CORS) and you want to make anything different than a plain GET - so for example a POST or adding custom headers - the browser will first make an OPTIONS request. This is what you see in your developer console:

当进行跨域请求 (CORS) 并且您想要做出与普通 GET 不同的任何内容时 - 例如 POST 或添加自定义标头 - 浏览器将首先发出 OPTIONS 请求。这是您在开发者控制台中看到的内容:

OPTIONS http://localhost:3000/session/create 404 (Not Found) angular.js:6730

The server then should add the appropriate headers to the response of the OPTIONS request.

然后服务器应该将适当的标头添加到 OPTIONS 请求的响应中。

So you can remove the custom headers from the Angular call. Next you need to make sure that your server/application answers the OPTIONS request, not returning a 404.

因此,您可以从 Angular 调用中删除自定义标头。接下来,您需要确保您的服务器/应用程序响应 OPTIONS 请求,而不是返回 404。