簡體   English   中英

我無法使用瀏覽器發送 POST 請求?

[英]I can't send a POST request using my browser?

我正在使用 Spring Boot MVC 開發一個應用程序,我有一個登錄頁面,每當我使用 chrome 在 forms 上輸入數據時,我的瀏覽器不會將我重定向到我在控制器 class 中指定的頁面,而是發送一個 GET request 它應該發送 POST 請求的地方。 這是我的 controller class

@Controller
@RequestMapping("/login")
public class loginController {
private final AuthService authService;

public loginController(AuthService authService) {
this.authService = authService;
}

 @GetMapping
  public String returnLogIn() {
  return "login";
  }

@PostMapping
public String login(@RequestParam String username, @RequestParam String password, Model model) {

User user = null;
try {
    user = this.authService.login(username, password);
    model.addAttribute("User", user);
    return "redirect:/home";
} catch (InvalidArgumentsException exception) {

    model.addAttribute("hasError", true);
    model.addAttribute("error", exception.getMessage());
    return "login";
}

正如你所看到的,如果登錄成功,那么我應該被重定向到主頁,但它並沒有發生,我再次被重定向到登錄頁面,所有的變化是其中的 URL 附加了我給出的參數. 但是,當我使用 POSTMAN 時,一切正常,發送了一個 POST 請求,我被重定向到 /home 頁面,就像我在 Controller class 中指定的那樣。但我不知道為什么當我使用 chrome 時不會發生這種情況。 每次我做一個小改動都必須使用 POSTMAN 真的很耗時。 這也是 HTML 表格

<form id="form-id"  th:action="@{/login}" th:method="post">
            <div class="mb-3">
                <input  type="text" class="form-control" name="username" id="username"  aria-describedby="emailHelp"
                       placeholder="User Name">
            </div>
            <div class="mb-3">
                <input type="password" class="form-control" name="password" id="password" placeholder="Password">
            </div>
            <!-- TODO use hasError set it in the model -->
            <div th:if="${hasError}">
            <span class="error text-danger" th:text="${error}"></span>
            </div>

            <div class="text-center"><button type="submit" class="btn btn-color px-5 mb-5 w-100 btn btn-dark" >Login</button></div>
            </form>

我不認為我的代碼有什么問題,因為當我使用 POSTMAN 時一切正常,但我真的不知道為什么當我使用我的瀏覽器時它不起作用。 Javascript 在我的瀏覽器中啟用了我真的不知道是什么問題。 我也嘗試將 POST 請求映射到不同的 URL 但我仍然遇到同樣的問題。

我也相信你的代碼示例沒有問題,因為如果有問題,它不應該從 POSTMAN 正確響應,除非你已經配置了應用程序服務器並限制了來自瀏覽器的請求。 我可以給你的建議是在使用Fiddler(Fiddler是一個強大的web調試代理)等工具發送請求時監控請求,看看兩個請求是否向服務器發送相同的參數。

暫無
暫無

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

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