I want to get login information that user enters at backend. Here is the backend code :-
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/handlers"
"encoding/json"
"log"
)
type LoginDetails struct {
Username string `json:"username"`
Password string `json:"password"`
}
func login(w http.ResponseWriter, req *http.Request) {
var loginData LoginDetails
err := json.NewDecoder(req.Body).Decode(&loginData)
if err!=nil{
panic(err)
}
}
func main() {
fmt.Println("Starting server at http://localhost:3000...")
router := mux.NewRouter()
router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/dist/static")))
router.HandleFunc("/login", login)
headersOk := handlers.AllowedHeaders([]string{"Authorization"})
methodsOk := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})
log.Fatal(http.ListenAndServe(":3000", handlers.CORS( headersOk, methodsOk)(router)))
}
Angular code :-
login.component.ts file :-
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';
import { HttpErrorResponse} from '@angular/common/http';
import { LoginService } from './login.service';
import { LoginDetails } from './login';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers : [LoginService, LoginDetails]
})
export class LoginComponent implements OnInit {
loginForm : FormGroup;
constructor(private loginData : LoginDetails, private loginservice: LoginService, private _formBuilder : FormBuilder){}
ngOnInit() {
this.loginForm = this._formBuilder.group({
username : ['username'],
password : ['password']
})
}
OnSubmit(){
this.loginData.username = this.loginForm.controls.username.value;
this.loginData.password = this.loginForm.controls.password.value;
this.loginservice.loginUser(this.loginData).subscribe(response => {
console.log(response)
},(err: HttpErrorResponse) => {
console.log(err);
});
}
}
login.service.ts file :-
import { Injectable } from '@angular/core';
import { HttpClient, HttpClientModule, HttpHeaders} from '@angular/common /http';
import { Observable } from 'rxjs';
import { LoginDetails } from './login'
@Injectable()
export class LoginService{
private _url : string = "http://localhost:3000/login";
constructor( private http : HttpClient){}
loginUser(loginData : LoginDetails): Observable <any>{
console.log(loginData)
return this.http.post(this._url, loginData, {responseType : 'text'});
}
}
Error I receive is this :- POST http://localhost:3000/login 404 (Not Found)
.