草庐IT

reactjs - 跨源请求被阻止, header Access-Control-Allow-Origin 丢失

coder 2024-07-07 原文

我正在编写一个博客应用程序,它的前端采用 react + typescript,后端采用 go iris。我正在执行获取博客内容的请求。后端在 localhost:5000 上运行,节点在 localhost:3000 上运行。但是它失败并出现错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/getposts. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

我已经在后端配置了CORS

Cors := cors.New(cors.Options{
        AllowedOrigins:   []string{"http://localhost:3000"},
        AllowCredentials: true,
        AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"},
        AllowedHeaders:   []string{"Cache-Control", "X-File-Name", "X-Requested-With", "X-File-Name", "Content-Type", "Authorization", "Set-Cookie", "Cookie"},
        Debug:            true,
    })
authConfig := basicauth.Config{
        Users:   map[string]string{USER_NAME: PASSWORD},
        Realm:   "Authorization Required", // defaults to "Authorization Required"
        Expires: time.Duration(30) * time.Minute,
    }

authentication := basicauth.New(authConfig)
app := iris.New()
app.Use(Cors)
app.Get("/getposts", authentication, GetPostsHandler)

这是我发送请求的方式

fetch("http://localhost:5000/getposts", {
  method: "get",
  credentials: "include",
  mode: "cors",
  headers: [
    ["Content-Type", "application/json"],
    ["Authorization", "Basic " + btoa("Sreyas:password")]
  ]
})
  .then(response => {
    if (response.ok) {
      response.json().then(rawdata => {
        this.setState({ blogdata: rawdata });
      });
    } else {
      console.log("No posts");
      this.setState({ blogdata: null });
    }
  })
  .catch(error => {
    console.log("Server Error");
    this.setState({ blogdata: null });
  });

我搜索并尝试了几个小时来解决这个问题,但没有成功。

最佳答案

感谢 Slotheroo 建议使用 nginx,这是我解决这个问题的唯一可能方法。我使用 nginx 来代理请求并将前端和后端路由到 8000 端口。我将在此处留下我的 nginx 服务器配置示例和对代码所做的更改,以便将来对任何人都有帮助:)

(请注意,使用像“localhost”这样的环回 ip 会影响加载和发送请求的性能,因此请使用机器的确切 ip 来克服此类性能问题)

nginx.conf

server {
        listen       8000;
        server_name  localhost;

        location / {
            proxy_pass http://localhost:3000;
        }
        location /getposts {
            proxy_pass http://localhost:5000/getposts;
        }

    }

将 localhost:8000 添加到后端的 Allowed Orgins

AllowedOrigins:   []string{"http://localhost:8000"},

请求现在发送到 8000 端口

fetch('http://localhost:8000/getposts',{
                    method: 'get',
                    credentials: "include",
                    mode: "cors",
                    headers: [
                        ["Content-Type", "application/json"], 
                        ["Authorization","Basic "+btoa('Sreyas:password')],
                    ]     
            }).then((response) => {
                if(response.ok){
                    response.json().then(rawdata =>{
                        this.setState({blogdata:rawdata})
                    })
                }else{
                    console.log("No posts")
                    this.setState({blogdata:null})
                }
            }).catch(error => {
                console.log("Server Error")
                this.setState({blogdata:null})
              })
    }

关于reactjs - 跨源请求被阻止, header Access-Control-Allow-Origin 丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51269613/

有关reactjs - 跨源请求被阻止, header Access-Control-Allow-Origin 丢失的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  3. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  4. ruby - Sinatra set cache_control to static files in public folder编译错误 - 2

    我不知道为什么,但是当我设置这个设置时它无法编译设置:static_cache_control,[:public,:max_age=>300]这是我得到的syntaxerror,unexpectedtASSOC,expecting']'(SyntaxError)set:static_cache_control,[:public,:max_age=>300]^我只想将“过期”header设置为css、javaascript和图像文件。谢谢。 最佳答案 我猜您使用的是Ruby1.8.7。Sinatra文档中显示的语法似乎是在Ruby1.

  5. ruby - HTTP 请求中的用户代理,Ruby - 2

    我是Ruby的新手。我试过查看在线文档,但没有找到任何有效的方法。我想在以下HTTP请求botget_response()和get()中包含一个用户代理。有人可以指出我正确的方向吗?#PreliminarycheckthatProggitisupcheck=Net::HTTP.get_response(URI.parse(proggit_url))ifcheck.code!="200"puts"ErrorcontactingProggit"returnend#Attempttogetthejsonresponse=Net::HTTP.get(URI.parse(proggit_url)

  6. ruby-on-rails - 获取并发布相同匹配项的请求 - 2

    在我的路线文件中我有:match'graphs/(:id(/:action))'=>'graphs#(:action)'如果是GET请求(工作)或POST请求(不工作),我想匹配它我知道我可以使用以下方法在资源中声明POST请求:post'/'=>:show,:on=>:member但是我怎样才能为比赛做到这一点呢?谢谢。 最佳答案 如果你同时想要POST和GETmatch'graphs/(:id(/:action))'=>'graphs#(:action)',:via=>[:get,:post]编辑默认值可以设置如下match'g

  7. ruby-on-rails - Rails FasterCSV "unquoted fields do not allow\r or\n" - 2

    我在使用FasterCSV和我的rakedb:seeds迁移时遇到问题。我收到错误:“rake中止!未加引号的字段不允许\r或\n(第2行)”在以下seeds.rb数据上:require'csv'directory="db/init_data/"file_name="gardenzing020812.csv"path_to_file=directory+file_nameputs'LoadingPlantrecords'#Pre-loadallPlantrecordsn=0CSV.foreach(path_to_file)do|row|Plant.create!:name=>row[1

  8. ruby-on-rails - 如何在 ActionController::TestCase 请求中设置内容类型 - 2

    我试图像这样在我的测试用例中执行获取:request.env['CONTENT_TYPE']='application/json'get:index,:application_name=>"Heka"虽然,它失败了:ActionView::MissingTemplate:Missingtemplatealarm_events/indexwith{:handlers=>[:builder,:haml,:erb,:rjs,:rhtml,:rxml],:locale=>[:en,:en],:formats=>[:html]尽管在我的Controller中我有:respond_to:html,

  9. ruby-on-rails - Ubuntu 14.04 Rails 丢失文件 - 2

    安装Rails时,一切都很好,但后来,我写道:rails-v和输出:/home/toshiba/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in`require':cannotloadsuchfile--rails/cli(LoadError)from/home/toshiba/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in`r

  10. ruby - 将 ruby​​ 日期转换为字符串而不丢失格式 - 2

    我正在尝试将RubyDate对象转换为字符串。日期格式为:Sun,15Sep2013但是,当我使用#to_s将其转换为字符串时,它会给出以下内容:"2013-09-15"相反,我希望它变成:"Sun,15Sep2013" 最佳答案 使用Date#strftime有很多选择require'date'date=Date.parse("Sun,15Sep2013")#=>#date.strftime("%a,%d%b%Y")#=>"Sun,15Sep2013" 关于ruby-将ruby​​日期

随机推荐