【问题标题】:How to fix 'Access-Control-Allow-Origin' errors when fetching from Rails API从 Rails API 获取时如何修复“Access-Control-Allow-Origin”错误
【发布时间】:2019-02-03 07:56:41
【问题描述】:

我正在尝试使用 Reactjs 作为我的前端注册我的 Rails API,但我不断收到此错误:“Access-Control-Allow-Origin”。我已经在 Rails 上启用了 CORS。

有趣的是,昨天我在 chrome 上启用了一个插件后它还在工作,但并不是每个人都有机会知道他们必须添加一个插件。这是我得到的确切错误:

 Access to fetch at 'http://localhost:3001/api/v1/auth' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这是我的代码:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3000/'
    resource '*',
     headers: :any,
     methods: %w(:get, :put, :post, :delete),
     expose: %w(access-token expiry token-type uid client),
     max_age: 0
   end
end

在 reactjs 上:

import React, { Component } from 'react'
import 'whatwg-fetch';



class SignUp extends Component {
    constructor(props) {
     super(props);
     this.state = {
       firstname: '', lastname: '', username: '', email: '', password: '', confirmpassword: ''
     };

     this.handleChange = this.handleChange.bind(this);
     this.handleSubmit = this.handleSubmit.bind(this);
   }

   validateForm() {
      return (
        this.state.password.length > 8 &&
        this.state.password === this.state.confirmpassword
      );
    }


   handleChange(event) {
     this.setState({ [event.target.name]: event.target.value });
   }

   handleSubmit(event) {
     event.preventDefault();
     let data = {
         'first_name': this.state.firstname, 'last_name': this.state.lastname, 'email': this.state.email,
         'nickname': this.state.username, 'password': this.state.password, 'password_confirmation': this.state.confirmpassword,
        }
  console.log(data)
      fetch('http://localhost:3001/api/v1/auth', {
        credentials: 'same-origin',
        method: 'POST',
        headers: {
          'Accept': 'application/json, */*',
          "Content-Type": "application/json",
          'Access-Control-Allow-Origin': '*'
       },
        body: JSON.stringify(data)})
        .then(function(data) {
        console.log('request succeeded with JSON response', data)
      }).catch(function(error) {
        console.log('request failed', error)
      })
   }

   render() {
     return (
       <form onSubmit={this.handleSubmit}>
         <label>
           First Name:
            <input type="text" name='firstname' onChange={this.handleChange} />
         </label>
         <br />
         <br />

         <label>
           Last Name:
           <input type="text" name='lastname' onChange={this.handleChange} />
         </label>
         <br />
         <br />

         <label>
           Username:
           <input type="text" name='username' onChange={this.handleChange} />
         </label>
         <br />
         <br />

         <label>
           Email:
           <input type="text" name='email' onChange={this.handleChange} />
         </label>
         <br />
         <br />

         <label>
           Password:
           <input type="text" name='password' onChange={this.handleChange} />
         </label>
         <br />
         <br />

         <label>
           Confirm Password:
           <input type="text" name='confirmpassword' onChange={this.handleChange} />
         </label>
         <br />
         <br />

         <input type="submit" value="Submit" />
       </form>
     );
   }
  }

  export default SignUp

我正在尝试注册,然后能够创建、显示、列出和删除帖子。有人可以帮我发现问题吗?还有如何在注册到另一个页面后重定向用户。任何见解将不胜感激]1

【问题讨论】:

  • react 这边无事可做。您需要配置服务器端以返回适当的Access-Control-Allow-Origin 标头
  • 你试过origins '*'而不是起源'http://localhost:3000/'吗?
  • @UdAY 我做了,没区别。

标签: reactjs rails-api


【解决方案1】:

使用扩展启用 CORS 后尝试重新加载缓存?

【讨论】:

    猜你喜欢
    • 2016-08-28
    • 2020-08-18
    • 1970-01-01
    • 2017-07-13
    • 2017-12-17
    • 2015-06-24
    • 2017-06-15
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多