我正在尝试使用Reactjs作为前端来注册我的Rails API,但我不断收到此错误:“ Access-Control-Allow-Origin”。我已经启用了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
答案 0 :(得分:0)
在启用扩展名的CORS之后尝试重新加载缓存吗?