簡體   English   中英

嘗試使用Angular 6和Spring Boot登錄時出現404錯誤

[英]Getting 404 error when trying to login using Angular 6 & Spring Boot

嘗試為角度為6的登錄組件實施spring boot認證時遇到40(x)錯誤。 MySQL數據庫中已經有一個帶有客戶名稱和密碼的客戶表。

以下是我正在嘗試找出問題的文件。 最后一張圖片是從客戶表輸入用戶數據后出現的錯誤。

Java Spring引導代碼

客戶總監

@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();
    }
}

Angular 6 /打字稿代碼

登錄組件

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.');
      }
}

錯誤

錯誤

我認為問題是因為您試圖將請求發送到http://localhost:4200 您在此端口上運行前端,但后端在另一端口上運行。 可能是8080。嘗試將LoginComponent的URL中的端口更改為8080。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM