我想获取用户在后端输入的登录信息。 这是后端代码:-
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)))
}
角度代码:-
login.component.ts 文件:-
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 文件:-
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'});
}
}
我收到的错误是:-POST http://localhost:3000/login 404 (Not Found)
。
答案 0 :(得分:0)
我专注于服务器部分,因为问题出在服务器端。
我将main.go
替换为
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"log"
"net/http"
)
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)
}
_, err = w.Write([]byte("ok\n"))
if err != nil{
panic(err)
}
}
func main() {
fmt.Println("Starting server at http://localhost:3000...")
router := mux.NewRouter()
router.HandleFunc("/login", login) // Registering /login before / seems to do the trick
router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/dist/static")))
headersOk := handlers.AllowedHeaders([]string{"Authorization"})
methodsOk := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})
log.Fatal(http.ListenAndServe(":3000", handlers.CORS(headersOk, methodsOk)(router)))
}
$ curl -X POST -H "Content-Type: application/json" -d '{"username": "user", "password": "p4ssw0rd"}' http://127.0.0.1:3000/login
ok
按照添加到路由器的顺序测试路由。如果两个 路线比赛,第一个获胜:
以下是与您的情况相匹配的示例:
r := mux.NewRouter()
r.HandleFunc("/specific", specificHandler)
r.PathPrefix("/").Handler(catchAllHandler)
您的“ /”处理程序似乎在“ / login”处理程序之前捕获了请求。