Yeoman, Grunt, AngularJS and error 404 on POST form

与世无争的帅哥 提交于 2019-12-13 07:37:45

问题


I am trying to send a form with "POST" method with AngularJS. I use $http to send it but it always return "Cannot POST" and 404 error. The route is correct and only happens if I execute my app via Grunt (sending by "GET" works perfect). The app has been built using Yeoman.

I think that it has to be a silly problem but I cannot make it work.

The view:

<form name="formLogin" ng-submit="login()">

<ul>
    <li>
        <label for="user">User</label>
        <input type="text" id="user" name="user" ng-model="user">
    </li>
    <li>
        <label for="pass">Password</label>
        <input type="password" id="pass" name="pass" ng-model="pass">
    </li>

</ul>

<input type="submit" value="Send">

The controller:

    'use strict';
angular.module('myApp')
  .controller('LoginCtrl', function ($scope, $http, $resource) {


    $scope.login = function() {

      var config = {
        url: 'php/login.php',
        method: 'POST',
        data: {
            user: $scope.user,
            pass: $scope.pass
        }
      }; // configuration object

      $http(config)
        .success(function(data, status, headers, config) {
            console.log('success');
            if (data.status) {
              // succefull login

            } else {
              // Wrong login
            }
        })
        .error(function(data, status, headers, config) {
            console.log('error');

        });

    };

  });

I use Grunt with:

grunt server

Why happens that?

Thanks!


回答1:


I'm confused why GET should work in this case. The Grunt server just serves static files from your app and .tmp directories and your reference to the .php file is relative. So with the standard setup, an AJAX request to php/login.php would just return you the plain PHP source code of the file located in app/php/login.php, which is certainly not what you want.

You probably want to separate your backend from your frontend and have your PHP application in a different location. This could either be under a different location (e.g. /api/login.php) or a different host https://api.example.com/login.php. Mixing your Yeoman application with your API isn't a good idea.

However, if you are forced to keep them within one project, you can use grunt-php to start a local PHP server from your Gruntfile.




回答2:


Angular by default sends http post requests as application/json and not as application/x-www-form-urlencoded which may cause problems. Change your application to accept application/json or replace application/json with application/x-www-form-urlencoded in $httpProvider.defaults.headers.post and serialize form yourself. More details in Angular.js doc in section Setting HTTP headers.



来源:https://stackoverflow.com/questions/18123042/yeoman-grunt-angularjs-and-error-404-on-post-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!