gpt4 book ai didi

java - 如何更正我的代码以消除 CORS 获取问题?

转载 作者:行者123 更新时间:2023-12-02 09:31:19 25 4
gpt4 key购买 nike

下午好!我收到错误“从原点“http://localhost:8080/registration”获取“http://localhost:3000”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“访问控制”请求的资源上存在“-Allow-Origin” header 。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。”我正在尝试将来自 Angular Web 应用程序的信息放入 java 应用程序(spring boot)中。我查看了许多不同的链接,但没有找到代码中的错误在哪里。这是我的 Registration.js,我想有一个错误,但找不到哪里。

import fetch from "node-fetch";

class Registration extends Component{
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
username: '',
password: '',
confirmPassword: '',
user_fullname: '',
user_email: '',
company_name: '',
position_name: '',
};
}
handleChange = (event, title) => this.setState({[title]: event.target.value});

handleSubmit = async event => {
event.preventDefault();
this.setState({isloading: true});
console.log(this.state);
const headers: HttpHeaders = new HttpHeaders().set('Content-Type', 'application/json;charset=UTF-8')
.append('Content-type', 'application/json;')
.append('Accept','application/json')
.append('Access-Control-Allow-Origin', '*')
return fetch('http://localhost:8080/registration',
{ mode:"no-cors" , headers: headers, method:"POST" ,body:this.state}
).then(response => {
console.log(response);
})
.catch(error => {
console.log(error)
})
};
render() {
return (
<form method="POST" onSubmit={this.handleSubmit} action="/registration">
<FormGroup controlId="username" bssize="large">
<FormControl name="username" value={this.state.username} type="text" onChange={ this.handleUsernameChange} />
</FormGroup>

<FormGroup controlId="password" bssize="large">
<FormControl name="password" value={this.state.password} onChange={this.handlePasswordChange} type="text" />
</FormGroup>

<FormGroup controlId="confirmPassword" bssize="large">
<FormControl name="confirmPassword" value={this.state.confirmPassword} onChange={this.handleConfirmPasswordChange} type="text"/>
</FormGroup>

<FormGroup controlId="user_fullname" bssize="large">
<FormControl name="user_fullname" value={this.state.user_fullname} type="text" onChange={this.handleUser_FullnameChange} />
</FormGroup>

<FormGroup controlId="user_email" bssize="large">
<FormControl name="user_email" value={this.state.user_email} type="text" onChange={this.handleUser_emailChange} />
</FormGroup>

<FormGroup controlId="company_name" bssize="large">
<FormControl name="company_name" value={this.state.company_name} type="text" onChange={this.handleCompany_nameChange} />
</FormGroup>

<FormGroup controlId="position_name" bssize="large">
<FormControl name="position_name" value={this.state.position_name} type="text" onChange={this.handlePosition_nameChange} />
</FormGroup>

<Button bssize="large" type="submit"> Registration </Button>
</form>
);
}}export default Registration;

我的UserController.java

    @RequestMapping(value = "/registration", method = {RequestMethod.POST}, produces={"application/json"})
@ResponseBody
public ResponseEntity<User> registration(@RequestBody User user, HttpStatus httpStatus) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
userService.saveUser(user);
return new ResponseEntity<User>(user, HttpStatus.CREATED);
}
@GetMapping("/registration")
public String registration(Model model) {
model.addAttribute("userForm", new User());

return "registration";
}

用户.java


@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "username")
private String username;

@Column(name = "password")
private String password;
@Transient
@Column(name = "confirmPassword")
private String confirmPassword;

@Column(name = "user_fullname")
private String user_fullname;

@Column(name = "user_email")
private String user_email;

@Column(name = "company_name")
private String company_name;

@Column(name = "position_name")
private String position_name;
@Column(name = "date")
private Date date = new Date(System.currentTimeMillis());


@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Roles> roles;
public User(){

}
public User(Integer id,String username, String password, String confirmPassword, String user_fullname, String user_email,String company_name, String position_name ){
this.id = id;
this.username=username;
this.password = password;
this.confirmPassword = confirmPassword;
this.user_fullname = user_fullname;
this.user_email = user_email;
this.company_name = company_name;
this.position_name = position_name;
}


public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getConfirmPassword() {
return confirmPassword;
}

public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}

public String getUser_fullname() {
return user_fullname;
}

public void setUser_fullname(String user_fullname) {
this.user_fullname = user_fullname;
}

public String getUser_email() {
return user_email;
}

public void setUser_email(String user_email) {
this.user_email = user_email;
}

public String getCompany_name() {
return company_name;
}

public void setCompany_name(String company_name) {
this.company_name = company_name;
}

public String getPos_name() {
return position_name;
}

public void setPos_name(String position_name) {
this.position_name = position_name;
}


public Set<Roles> getRoles() {
return roles;
}
public void setRoles(Set<Roles> roles) {
this.roles = roles;
}

public Date getDate() {
return date;
}


}

用户数据库

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL ,
password VARCHAR(255) NOT NULL ,
user_fullname VARCHAR(255),
user_email VARCHAR(255) ,
company_name VARCHAR(255),
position_name VARCHAR(255),
date DATETIME
)
ENGINE = InnoDB;

最佳答案

您似乎遇到了 Spring Boot 安全问题。假设您启用了 Spring Boot 安全性,根据您收到的错误消息“对预检请求的响应未通过访问控制检查”,您需要在后端允许预检请求。您可以尝试创建一个新类并扩展 WebSecurityConfigurerAdaptor,如下所示:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(Http.OPTIONS, "/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}

Http.OPTIONS 是发送到服务器的飞行前请求,以确保您拥有正确的身份验证来检索资源。在这里,您允许所有预检请求让实际请求检索资源。

关于java - 如何更正我的代码以消除 CORS 获取问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57947010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com