我尝试通过go创建全栈猜谜游戏,因此当我同时运行FE和BE并输入index.html,然后单击登录继续时,它不会显示任何内容。这是我的main.go代码
package main
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"time"
"github.com/gorilla/mux"
)
type GuessRequestBody struct {
Guess int `json:"guess"`
}
type GuessResponseBody struct {
Status string `json:"status"`
NumGuesses int `json:"numGuesses,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
}
type LoginRequestBody struct {
Username string `json:"username"`
Password string `json:"password"`
}
type LoginResponseBody struct {
Token string `json:"token"`
}
var numToGuess int
var numGuesses int
var authenticated bool
func main() {
r := mux.NewRouter()
r.HandleFunc("/login", loginHandler).Methods("POST")
r.HandleFunc("/guess", guessHandler).Methods("POST")
log.Fatal(http.ListenAndServe(":8081", r))
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var requestBody LoginRequestBody
err := json.NewDecoder(r.Body).Decode(&requestBody)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
if requestBody.Username == "admin" && requestBody.Password == "password" {
token := "my-random-token"
responseBody := LoginResponseBody{Token: token}
json.NewEncoder(w).Encode(responseBody)
authenticated = true
} else {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
func guessHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if !authenticated {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var requestBody GuessRequestBody
err := json.NewDecoder(r.Body).Decode(&requestBody)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
if numToGuess == 0 {
numToGuess = rand.Intn(100) + 1
}
numGuesses++
if requestBody.Guess < numToGuess {
responseBody := GuessResponseBody{Status: "tooLow"}
json.NewEncoder(w).Encode(responseBody)
} else if requestBody.Guess > numToGuess {
responseBody := GuessResponseBody{Status: "tooHigh"}
json.NewEncoder(w).Encode(responseBody)
} else {
responseBody := GuessResponseBody{Status: "success", NumGuesses: numGuesses}
json.NewEncoder(w).Encode(responseBody)
numToGuess = 0
numGuesses = 0
}
}
func init() {
rand.Seed(time.Now().UnixNano())
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Fullstack Guessing Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="login-container">
<h1>Login</h1>
<form id="login-form" action="http://localhost:8080" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br>
<button type="submit">Login</button>
</form>
</div>
<div id="guess-container" style="display:none;">
<h1>Guess the Number</h1>
<p>Guess a number between 1 and 100:</p>
<input type="number" id="guess" name="guess" min="1" max="100">
<br>
<button type="button" id="submit-guess">Submit</button>
<p id="result" style="display:none;"></p>
</div>
<script src="app.js"></script>
</body>
</html>
style.css
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
}
h1 {
font-size: 2em;
}
form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 2em;
}
label {
font-size: 1.5em;
margin-bottom: 1em;
}
input[type="number"] {
font-size: 1.5em;
padding: 0.5em;
margin-bottom: 1em;
}
button[type="submit"] {
font-size: 1.5em;
padding: 0.5em 1em;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 0.3em;
cursor: pointer;
}
p#response {
font-size: 1.5em;
margin-top: 2em;
}
app.js
const loginForm = document.getElementById('login-form');
const loginContainer = document.getElementById('login-container');
const guessContainer = document.getElementById('guess-container');
const submitGuessBtn = document.getElementById('submit-guess');
const result = document.getElementById('result');
loginForm.addEventListener('submit', (event) => {
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({username, password})
})
.then(response => response.json())
.then(data => {
if (data.token) {
localStorage.setItem('token', data.token);
loginContainer.style.display = 'none';
guessContainer.style.display = 'block';
}
})
.catch(error => console.error(error));
});
submitGuessBtn.addEventListener('click', () => {
const guess = document.getElementById('guess').value;
const token = localStorage.getItem('token');
fetch('/guess', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({guess})
})
.then(response => response.json())
.then(data => {
if (data.result) {
result.innerHTML = `Your guess was ${data.result}.`;
result.style.display = 'block';
}
})
.catch(error => console.error(error));
});
有错误
[2023-02-14T07:20:33.479Z] "POST /login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Safari/605.1.15"
[2023-02-14T07:20:33.480Z] "POST /login" Error (404): "Not found"
我希望在我登录用户名:用户名,密码:密码后,它会显示猜测号码页面,并可以与用户交互
1条答案
按热度按时间wrrgggsh1#
你的后端正在端口8081上运行。你的前端正在其他服务器上运行或根本没有运行服务器。你需要将前端连接到后端。
最简单的方法是从后端提供静态文件:
1.创建一个文件夹
static
并将3个文件移动到其中:index.html
、app.js
和style.css
1.在
main.go
的main()
函数中的log.Fatal
之前添加以下行:1.启动后端(通常我们执行
go run main.go
)1.在浏览器中打开此页:
localhost:8081/index.html
1.输入
admin
和password
,这就是你的游戏。然后更正游戏源代码中的错误。
另外,一个好主意是在后端使用一个 * logger *。下面是一个例子。你需要在你的
main.go
中添加loggingMiddleware
函数,然后在main()
函数中使用r.Use(loggingMiddleware)
打开它。这样你就可以在控制台窗口中看到传入后端的请求。