尝试使用Angular 6&;登录时出现404错误;弹簧靴

尝试使用Angular 6&;登录时出现404错误;弹簧靴,angular,spring,spring-boot,Angular,Spring,Spring Boot,尝试为angular 6登录组件实现spring引导身份验证时出现40(x)个错误。MySQL数据库中已有一个客户表,其中包含客户名称和密码 下面是我正在努力解决问题的文件。最后一个图像是我从customer表输入用户数据后得到的错误 Java Spring启动代码 客户控制员 Angular 6/Typescript代码 登录组件 从'@angular/core'导入{Component,OnInit}; 从'@angular/Router'导入{Router,ActivatedRoute};

尝试为angular 6登录组件实现spring引导身份验证时出现40(x)个错误。MySQL数据库中已有一个客户表,其中包含客户名称和密码

下面是我正在努力解决问题的文件。最后一个图像是我从customer表输入用户数据后得到的错误

Java Spring启动代码 客户控制员 Angular 6/Typescript代码 登录组件
从'@angular/core'导入{Component,OnInit};
从'@angular/Router'导入{Router,ActivatedRoute};
从'@angular/common/http'导入{HttpClient};
从“rxjs”导入{Observable};
@组成部分({
选择器:“登录”,
templateUrl:“./login.component.html”
})
导出类LoginComponent实现OnInit{
模型:any={};
建造师(
专用路由:激活的路由,
专用路由器:路由器,
私有http:HttpClient
) { }
恩戈尼尼特(){
sessionStorage.setItem('token','');
}
登录(){
常量url=http://localhost:4200/login';
this.http.post(url{
用户名:this.model.userName,
密码:this.model.password
}).subscribe(isValid=>{
如果(有效){
sessionStorage.setItem('token',btoa(this.model.username+':'+this.model.password));
这个.router.navigate(['']);
}否则{
警报(“身份验证失败”);
}
});
}
}
主分量
从'@angular/core'导入{Component,OnInit};
从“@angular/common/http”导入{HttpClient,HttpHeaders,HttpErrorResponse};
从“rxjs”导入{observatable,throwerr};
从“rxjs/operators”导入{catchError,map,tap};
@组成部分({
选择器:“主页”,
templateUrl:“./home.component.html”
})
导出类HomeComponent实现OnInit{
用户名:字符串;
构造函数(私有http:HttpClient){}
恩戈尼尼特(){
常量url=http://localhost:4200';
const headers:HttpHeaders=新的HttpHeaders({
'Authorization':'Basic'+sessionStorage.getItem('token')
});
const options={headers:headers};
this.http.post(url,{},选项)。
订阅(委托人=>{
this.userName=principal['name'];
},
错误=>{
如果(error.status==401){
警报(“未授权”);
}
}
);
}
注销(){
sessionStorage.setItem('token','');
}
私有句柄错误(错误:HttpErrorResponse){
if(error.error instanceof ErrorEvent){
console.error('发生错误:',error.error.message);
}否则{
控制台错误(
`后端返回代码${error.status},`+
`正文是:${error.error}`);
}
回击投手(
“发生了不好的情况;请稍后再试。”);
}
}
错误
我认为问题是因为您试图向
http://localhost:4200
。您在此端口上运行前端,但后端正在另一个端口上运行。可能是8080。尝试将LoginComponent中url中的端口更改为8080。

我认为问题在于您试图将请求发送到
http://localhost:4200
。您在此端口上运行前端,但后端正在另一个端口上运行。可能是8080。尝试将LoginComponent中url中的端口更改为8080。

您应该在此处复制代码,而不是使用屏幕截图。看起来登录url可能是
http://localhost:4200/api/login
——你能试试吗?因为
@RequestMapping
装饰器链,我认为。。。一般来说,我们鼓励人们将代码片段作为文本而不是图像发布。但是你在截图方面做得很好:-)对不起,我已经更新了帖子,你应该在这里复制你的代码,不要使用截图。看起来登录url可能是
http://localhost:4200/api/login
——你能试试吗?因为
@RequestMapping
装饰器链,我认为。。。一般来说,我们鼓励人们将代码片段作为文本而不是图像发布。但你们在截图方面做得很好:-)对不起,我已经更新了这篇文章
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
public class CustomerController {

    @Autowired
    CustomerRepository repository;

    @RequestMapping("/login")
    public boolean login(@RequestBody Customer user) {
        return
          user.getCname().equals("user") && user.getPassword().equals("password");
    }

    @RequestMapping("/user")
    public Principal user(HttpServletRequest request) {
        String authToken = request.getHeader("Authorization")
          .substring("Basic".length()).trim();
        return () ->  new String(Base64.getDecoder()
          .decode(authToken)).split(":")[0];
    }

    @GetMapping("/customers")
    public List<Customer> getAllCustomers() {
        System.out.println("Get all Customers...");

        List<Customer> customers = new ArrayList<>();
        repository.findAll().forEach(customers::add);

        return customers;
    }

    @PostMapping(value = "/customers/create")
    public Customer postCustomer(@RequestBody Customer customer) {

        Customer _customer = repository.save(new Customer(customer.getCname(), customer.getAddress(), customer.getPhone(),customer.getPassword()));
        return _customer;
    }

    @DeleteMapping("/customers/{cid}")
    public ResponseEntity<String> deleteCustomer(@PathVariable("cid") long cid) {
        System.out.println("Delete Customer with CID = " + cid + "...");

        repository.deleteByCid(cid);

        return new ResponseEntity<>("Customer has been deleted!", HttpStatus.OK);
    }

    @DeleteMapping("/customers/delete")
    public ResponseEntity<String> deleteAllCustomers() {
        System.out.println("Delete All Customers...");

        repository.deleteAll();

        return new ResponseEntity<>("All customers have been deleted!", HttpStatus.OK);
    }

    @GetMapping(value = "customers/cname/{cname}")
    public List<Customer> findByAge(@PathVariable String cname) {

        List<Customer> customers = repository.findByCname(cname);
        return customers;
    }

    @PutMapping("/customers/{cid}")
    public ResponseEntity<Customer> updateCustomer(@PathVariable("cid") long cid, @RequestBody Customer customer) {
        System.out.println("Update Customer with CID = " + cid + "...");

        Optional<Customer> customerData = repository.findByCid(cid);

        if (customerData.isPresent()) {
            Customer _customer = customerData.get();
            _customer.setCname(customer.getCname());
            _customer.setAddress(customer.getAddress());
            _customer.setPhone(customer.getPhone());
            return new ResponseEntity<>(repository.save(_customer), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}
@Configuration
@EnableWebSecurity
public class BasicAuthConfiguration 
  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user")
          .password("password")
          .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) 
      throws Exception {
        http.csrf().disable()
          .authorizeRequests()
          .antMatchers("/login").permitAll()
          .anyRequest()
          .authenticated()
          .and()
          .httpBasic();
    }
}
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
    selector: 'login',
    templateUrl: './login.component.html'
})

export class LoginComponent implements OnInit {

    model: any = {};


    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private http: HttpClient
    ) { }

    ngOnInit() {
        sessionStorage.setItem('token', '');
    }

    login() {
        const url = 'http://localhost:4200/login';
        this.http.post<Observable<boolean>>(url, {
            userName: this.model.username,
            password: this.model.password
        }).subscribe(isValid => {
            if (isValid) {
                sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password));
                this.router.navigate(['']);
            } else {
                alert('Authentication failed.');
            }
        });
    }
}
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap} from 'rxjs/operators';
@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})

export class HomeComponent implements OnInit {

    userName: string;
    constructor(private http: HttpClient) { }

    ngOnInit() {
        const url = 'http://localhost:4200';

        const headers: HttpHeaders = new HttpHeaders({
            'Authorization': 'Basic ' + sessionStorage.getItem('token')
        });

        const options = { headers: headers };
        this.http.post<Observable<Object>>(url, {}, options).
            subscribe(principal => {
                this.userName = principal['name'];
            },
            error => {
                if (error.status === 401) {
                    alert('Unauthorized');
                }
            }
        );
    }

    logout() {
        sessionStorage.setItem('token', '');
    }
    private handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          console.error('An error occurred:', error.error.message);
        } else {
          console.error(
            `Backend returned code ${error.status}, ` +
            `body was: ${error.error}`);
        }
        return throwError(
          'Something bad happened; please try again later.');
      }
}