【问题标题】:Http POST 405 errror in Angularjs with Spring MVC使用 Spring MVC 的 Angularjs 中的 Http POST 405 错误
【发布时间】:2018-01-11 23:49:51
【问题描述】:

实际上我想将 Spring 与 Angularjs 集成,我是 Angularjs 的初学者。当我使用 $http post 方法时,它返回 POST 405。这是我的代码

SignUp.html

<form method="post" ng-submit="saveUser()">
                                <input type="hidden" name="${_csrf.parameterName}"
                                    value="${_csrf.token}" />
</form>

myApp.js

var myApp = angular.module('myApp', ['ngMessages']);

UserIdController.js

myApp.controller('UserIdController', [
    '$scope',
    'UserIdService',
    function($scope, UserIdService) {
        $scope.saveUser = function() {
            UserIdService.saveUser($scope.user).then(
                    function success(response) {
                        console.log("user Added");
                    }, function error(response) {
                        console.log("User not Added")
                    });
        }
    } ]);   

UserIdService.js

myApp
    .service(
            'UserIdService',
            [
                    '$http',
                    function($http) {
                        this.saveUser = function saveUser(user) {
                            return $http({
                                method : 'post',
                                url : 'SignUpUser',
                                data : {
                                    firstName : user.firstName
                                },
                                headers : 'Content-Type: application/json'
                            });
                        }
                    } ]);

Spring REST 控制器

    @RestController
    @Produces("text/plain")
    public class SignUpController {

       private static final Logger logger = 
       LogManager.getLogger(SignUpController.class);

      @RequestMapping(value = "/SignUpUser", method = 
      RequestMethod.POST, headers = "Accept=application/json")
      public String saveUser(@PathVariable String firstname) throws 
        ParseException {

        logger.debug("Enter in SignUp Controller in Post Method");
        UserDetails userDetails = new UserDetails();
        studentDetails.setFirstName(firstname);
       return "ok";
     }

我在 Chrome 中的 Inspect 元素中收到此错误

      Request URL:http://localhost:8080/examapp/signup
      Request Method:POST
      Status Code:405 
      Remote Address:[::1]:8080
      Referrer Policy:no-referrer-when-downgrade
      Response Headers
     view parsed
     HTTP/1.1 405
     Cache-Control: no-cache, no-store, max-age=0, must-revalidate
     Pragma: no-cache
     Expires: 0
     X-XSS-Protection: 1; mode=block
     X-Frame-Options: DENY
     X-Content-Type-Options: nosniff
     Allow: GET
     Content-Type: text/html;charset=ISO-8859-1
     Content-Language: en
     Content-Length: 1084 
     Date: Fri, 04 Aug 2017 05:50:32 GMT
     Request Headers
     view source
     Accept:application/json, text/plain, */*
     Accept-Encoding:gzip, deflate, br
     Accept-Language:en-US,en;q=0.8
     Connection:keep-alive 
     Content-Length:26
     Content-Type:application/json
     Cookie:JSESSIONID=ACF3E30CB7B3A6A9862F923F42DB61B5
     Host:localhost:8080
     Origin:http://localhost:8080
     Referer:http://localhost:8080/examapp/signup.html
     User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
     (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36
     Request Payload

有人知道我做错了什么吗?这似乎是一个非常直接的实现,适用于我见过的所有教程。任何帮助将不胜感激。 谢谢。

【问题讨论】:

  • 服务器是否允许注册 API 的 POST 方法?
  • 你能用邮递员打你的api吗

标签: angularjs spring spring-mvc spring-boot


【解决方案1】:

请在您的SignUpController 上添加@RequestMapping("/examapp")

@RestController
@Produces("text/plain")
@RequestMapping("/examapp")
    public class SignUpController {

【讨论】:

    【解决方案2】:

    您已在此处指定@PathVariable。路径变量就是这样,来自路径的变量。你要的是@RequestBody

    在您的场景中,Spring 没有映射到 /SignUpUser,它正在寻找 /SignUpUser/{firstName},但由于 @RequestMapping 未指定 {firstName},因此您实际上是在发布到不存在的资源。

    虽然在现实世界中不切实际,但在您的$http.post 中仅发布一个名字以登录,您只需要data : user.firstName

    在你的 Spring 控制器中:

    @RequestMapping(value = "/SignUpUser", method = 
          RequestMethod.POST, headers = "Accept=application/json")
          public String saveUser(@RequestBody String firstname)
    

    正确的解决方法

    如果您希望您的后端接受您在 Angular 中拥有的(更真实的),您将创建一个 POJO 类,并接受它(@RequestBody UserDetails request)。看来您已经创建了 UserDetails POJO,所以您只需要接受这一点:

    @RequestMapping(value = "/SignUpUser", method = 
          RequestMethod.POST, headers = "Accept=application/json")
          public String saveUser(@RequestBody UserDetails userDetails ) {
    

    【讨论】:

    • 我改变了我的代码,因为你告诉 bt 错误。实际上我在 Angularjs 中遇到错误,错误是 xhr.send(isUndefined(post) ? null : post);
    • 更改帖子 -> POST。
    • 如果您使用 --debug 标志运行您的应用程序,您会得到什么?你在 Spring 的控制台中有什么东西吗?
    • 另外,您可以从 CLI 或 *nix 的脚本(curl、powershell)发布吗?
    • I get error in console http-nio-8080-exec-4] WARN org.springframework.web.servlet.PageNotFound - 不支持请求方法'POST'并且我的浏览器显示 POST 405() 错误
    猜你喜欢
    • 2017-09-09
    • 2017-08-27
    • 2011-04-10
    • 2011-09-30
    • 2019-02-26
    • 2015-01-31
    • 2015-02-16
    • 2015-11-07
    • 2020-07-24
    相关资源
    最近更新 更多