我正在使用Spring-boot和Angular 2;前端和后端在不同的端口上运行。当我使用Advanced REST Client
(谷歌浏览器插件)检查网址时,我得到http://localhost:4000/user/register
的404,当我在前端输入信息时没有任何反应。
Web服务配置:
@Configuration
public class CorsConfig {
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest)req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "origin, x-requested-with, accept, Authorization, Content-Type");
response.setHeader("Access-Control-Max-Age", "3600");
if (!request.getMethod().equals("OPTIONS")) {
try {
chain.doFilter(req, res);
} catch (IOException e) {
System.out.println("IO Exception in CorsFilter: "+e);
e.printStackTrace();
} catch (ServletException e) {
System.out.println("Servlet Exception is CorFilter "+e);
e.printStackTrace();
}
}
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
}
以上是我配置后端的方法。
我正在尝试注册一个新的user
(Angular 2)
@Injectable()
export class RegisterService {
constructor (private http:Http) { }
sendUser (newUser: RegisterModel) {
let url = "http://localhost:4000/user/register";
let header = new Headers({'Content-Type': 'application/json'});
return this.http.post(url, JSON.stringify(newUser),{headers: header});
}
}
它的组成部分:
@Component ({
moduleId: module.id,
selector: 'register',
templateUrl: './register.html'
})
export class RegisterComponent {
newUser: RegisterModel = new RegisterModel();
constructor (private registerService: RegisterService){
}
onSubmit() {
this.registerService.sendUser(this.newUser).subscribe(
data => {
this.newUser = new RegisterModel();
console.log("New user was created.")
},
error => console.log(error)
);
}
}
Restfull service
@RestController("/user")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value = "/register", method = RequestMethod.POST)
public User registerUser(@RequestBody User user){
System.out.println("YAY-----------"+user.getFirstName());
return userService.save(user);
}
}
没有打印出来,也没有给出任何错误。
在我的application.properties中我有
server.port=4000
页面呈现但似乎后端没有响应。
如果有人想看,我发布的帖子也会在GIT上发布。
--------------------- Update 1 --------------------
我已将SecurityConfig更新为:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll()
.anyRequest().authenticated().and()
.formLogin().loginPage("/").permitAll().and()
.logout().permitAll();
http.authorizeRequests().antMatchers("/user/register")
.permitAll().anyRequest().anonymous();
http.authorizeRequests().antMatchers("/")
.permitAll().anyRequest().authenticated();
http.formLogin().loginPage("/")
.permitAll().and().logout().permitAll();
}
}
2)我还删除了pom file
目录中的frontend
。
结果:当我使用The requested URL can't be reached
(谷歌浏览器插件)时,我现在获得Advanced REST client
。
在GIT上更新了它。
答案 0 :(得分:0)
我假设您在进行身份验证之前发送register
请求?您的安全配置会将所有请求重定向到/
,这些请求不会在后端提供。所以它找不到,你收到404
。
这是您WebSecurityConfigurerAdapter
的安全配置:
http.authorizeRequests().antMatchers("/").permitAll()
.anyRequest().authenticated().and()
.formLogin().loginPage("/").permitAll().and()
.logout().permitAll();
register
请求您可以将安全配置更改为此,让register
在进行身份验证之前通过:
http.authorizeRequests().antMatchers("/user/register")
.permitAll().anyRequest().anonymous();
http.authorizeRequests().antMatchers("/")
.permitAll().anyRequest().authenticated();
http.formLogin().loginPage("/")
.permitAll().and().logout().permitAll();
基本上,允许anonymous
发送注册请求。
comments
部分中突出显示)评论后更新
您的UserController没有定义任何映射。你错误地使用了@RestController("/user")
,但它应该是:
@RestController
@RequestMapping("/user")
public class UserController {
您仍然可以从SecurityConfig中的先前配置中遗留下来:
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll()
.anyRequest().authenticated().and()
.formLogin().loginPage("/").permitAll().and()
.logout().permitAll();
http.authorizeRequests().antMatchers("/user/register")
.permitAll().anyRequest().anonymous();
http.authorizeRequests().antMatchers("/")
.permitAll().anyRequest().authenticated();
http.formLogin().loginPage("/")
.permitAll().and().logout().permitAll();
}
将其更改为:
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/user/register")
.permitAll().anyRequest().anonymous();
http.authorizeRequests().antMatchers("/")
.permitAll().anyRequest().authenticated();
http.formLogin().loginPage("/")
.permitAll().and().logout().permitAll();
}
第一行禁用csrf(跨站点请求伪造)。现在,我对该主题的知识不足以给你一个解释,但如果你不禁用它,你将得到403禁止的回复。我建议您禁用它,并在以后修复当前问题时再回到此处。
它,你的后端将接收并响应/ user / register请求(我可以在控制台中看到前端的日志:"新用户被创建" 。
10月18日编辑
我克隆了你的项目并且它有效。以下是我执行的完全步骤:
git clone https://github.com/drewjocham/AngularIssue.git
test.java.com.request
到com.request
AngularIssue\backend
mvn clean install
mvn spring-boot:run
(后端现在运行)AngularIssue\frontend
npm install
npm start
(现在正在运行前端)http://localhost:3000
inspect->console
视图
New user was created.
YAY-----------a