html - 当我尝试单击 HTML 中的提交按钮时出现 “Cannot POST/”

标签 html angularjs node.js

我见过类似的问题,但无法理解错误和解决方法。

我有一个基本的平均堆栈应用程序。我有一个提交按钮,如果我单击该按钮,它会在浏览器中抛出一个错误:

Cannot POST /

尽管如此,发布请求已发送到服务器,并且它会在我的数据库中更新。我只是想让浏览器在我点击提交并发布请求完成后返回到上一页!

浏览器控制台还显示错误:

POST http://localhost:3000/ 404 (Not Found)

这是我的引用文件 ctrl1.js:

    var app = angular.module('myApp', []);
app.controller('myCtrl',['$scope', '$http', function($scope, $http) {
    console.log("Hello from controller");

    $scope.application = {};

    var refresh = function(){
        $http.get('/applicationList').then(function(response){
            console.log("I got the applications I requested");
            $scope.applicationList = response.data;
            // $scope.contact = null;
        });

    };
    refresh();
    $scope.saveApplication = function(){
        console.log($scope.application);

        $scope.application.state = "saved";
        $http.post('/applicationList', $scope.application).then(function(response){
            console.log(response);
            //refresh();
        });
    };


    $scope.submitApplication = function(){
        console.log("reached here");
        console.log($scope.application);
        console.log("reached here");
        $scope.application.state = "submit";
        $http.post('/applicationList', $scope.application).then(function(response){
            console.log(response);
            refresh();
        });
    };

    $scope.remove = function(id){
        console.log(id);
        $http.delete('/applicationlist/'+id).then(function(response){
            refresh();
        });

    };

    $scope.edit = function(id){
        console.log(id);
        $http.get('/applicationlist/'+id).then(function(response){
            $scope.application = response.data;
            //refresh();
        });
    };

    $scope.update = function(){
        console.log($scope.application._id);
        $http.put('/applicationlist/' + $scope.application._id, $scope.application).then(function(response){
            //$scope.contact = response.data;
            refresh();
        });
    };

    // $scope.clear = function(){
    //     $scope.application = "";
    // };

    //Universities
    $scope.application.selectname1={};
    $scope.application.selectname2={};
    $scope.application.selectname3={};

    $scope.filter1 = function(item){
      return (!($scope.application.selectname1&&$scope.application.selectname1.id)||item.id !=$scope.application.selectname1.id||item.id==100);
    };

    $scope.filter2 = function(item){
      return (!($scope.application.selectname2&&$scope.application.selectname2.id)||item.id!=$scope.application.selectname2.id||item.id==100);
    };
    $scope.filter3 = function(item){
      return (!($scope.application.selectname3&&$scope.application.selectname3.id)||item.id !=$scope.application.selectname3.id||item.id==100);
    };
    $scope.universities = [
        {
            id:1,
            name: 'IITs'
        },
        {
            id:2,
            name: 'IIITs'
        },
        {
            id:3,
            name: 'BITS'
        },
        {
            id:100,
            name: 'None'
        }
    ];


    //Degrees
    $scope.application.selectdegree1={};
    $scope.application.selectdegree2={};
    $scope.application.selectdegree3={};

    $scope.filterDegree1 = function(item){
      return (!($scope.application.selectdegree1&&$scope.application.selectdegree1.id)||item.id !=$scope.application.selectdegree1.id||item.id==100);
    };

    $scope.filterDegree2 = function(item){
      return (!($scope.application.selectdegree2&&$scope.application.selectdegree2.id)||item.id!=$scope.application.selectdegree2.id||item.id==100);
    };
    $scope.filterDegree3 = function(item){
      return (!($scope.application.selectdegree3&&$scope.application.selectdegree3.id)||item.id !=$scope.application.selectdegree3.id||item.id==100);
    };
    $scope.degrees = [
        {
            id:1,
            name: 'PhD'
        },
        {
            id:2,
            name: 'Masters'
        },
        {
            id:3,
            name: 'BTech'
        },
        {
            id:100,
            name: 'None'
        }
    ];


    $scope.check = function(evt,cityName)
    {
        var i, tabcontent, tablinks;
        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }
        tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }
        document.getElementById(cityName).style.display = "block";
        return true;
    }



}]);

服务器.js:

var express = require('express');
var app = express();

var mongojs = require('mongojs');
var db = mongojs('internapplications', ['internforms']);

var assert = require('assert');


var bodyParser = require('body-parser');

var request = require('request');

app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

app.get('/applicationList', function(req, res){
    console.log("I received a get request");
    db.internforms.find(function(err, docs){
        console.log(docs);
        res.json(docs);
    });

});

app.post('/applicationList', function(req, res){
    console.log("I received a post request");
    console.log(req.body);
    db.internforms.insert(req.body, function(err,doc){
        res.json(doc);
    });
});



app.delete('/applicationList/:id', function(req,res){
    console.log("reached here");
    var id = req.params.id;
    console.log(id);
    db.internforms.remove({_id: mongojs.ObjectId(id)}, function(err,doc){
        res.json(doc);
    });
});

app.put('/applicationList/:id', function(req,res){
    var id = req.params.id;
    console.log(req.body.name);
    db.internforms.findAndModify({query: {_id: mongojs.ObjectId(id)},
    update: {$set: {name: req.body.name, email: req.body.email, number: req.body.number}},
    new: true},
    function(err,doc){
        res.json(doc);
    });
});

app.listen(3000);
console.log("Server running at port 3000");

我的 html 看起来像这样:

<!DOCTYPE html>
<html ng-app="myApp">
<head>

    <!-- Latest compiled and minified CSS - loading at the top, since we want stylesheets to load up as soon as the page comes up -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <link href="css/index.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="controllers/ctrl1.js"></script>



    <title>Intern Applications App</title>
</head>
<body ng-controller="myCtrl">

    <div class="container">
        <nav id="tab-navigation">
            <a href ng-click="check(event, 'page1')" id="defaultOpen">Applications Form</a>
            <a href ng-click="check(event, 'page2')" >Application List</a>

        </nav>




    <div class="tabcontent" id="page1">

    <form class="well form-horizontal" action=" " method="post"  id="contact_form">
        <!-- <fieldset> -->

        <!-- Form Name -->
        <legend>Intern Application Form</legend>

        <div class="form-group">
          <label class="col-md-4 control-label">Project Title</label>
            <div class="col-md-4 inputGroupContainer">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                    <textarea class="form-control" name="comment" placeholder="Project Title" ng-model="application.title" ></textarea>
          </div>
          </div>
        </div>

        <div class="form-group">
          <label class="col-md-4 control-label">Project Description</label>
            <div class="col-md-4 inputGroupContainer">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                    <textarea class="form-control" name="comment" ng-model="application.description" placeholder="Project Description" ></textarea>
          </div>
          </div>
        </div>

        <!-- Text input-->

        <div class="form-group">
          <label class="col-md-4 control-label">Approach</label>
            <div class="col-md-4 inputGroupContainer">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                    <textarea class="form-control" name="comment" ng-model="application.approach" placeholder="Approach" ></textarea>
          </div>
          </div>
        </div>

        <div class="form-group">
           <label class="col-md-4 control-label">Is the dataset available?</label>
           <div class="col-md-4">
               <div class="radio">
                   <label>
                       <input type="radio" id="yes" name="dataset" value="yes" ng-model="application.isData"/> Yes
                   </label>
               </div>
               <div class="radio">
                   <label>
                       <input type="radio" id="no" name="dataset" value="no" ng-model="application.isData"/> No
                   </label>
               </div>

           </div>
       </div>

        <!-- Text input-->

        <div class="form-group" ng-show="application.isData == 'no'">
          <label class="col-md-4 control-label">Approach for Data Collection</label>
          <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
          <input name="first_name" ng-model="application.dataDescription" placeholder="Approach" class="form-control"  type="text">
            </div>
          </div>
        </div>

        <div class="form-group" ng-show="application.isData == 'yes'">
          <label class="col-md-4 control-label">Data Available at</label>
          <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
          <input  name="first_name" placeholder="Approach" class="form-control"  type="text">
            </div>
          </div>
        </div>

        <!-- Text input-->

        <div class="form-group">
          <label class="col-md-4 control-label">Impact</label>
            <div class="col-md-4 inputGroupContainer">
            <div class="checkbox">
                <label>
                    <input type="checkbox" id="yes" value="Technical" ng-model="application.technical"/> Technical
                </label>
                <label>
                    <input type="checkbox" id="yes" value="Business" ng-model="application.business"/> Business
                </label>
            </div>

            </div>
          </div>

        <!-- Text input-->

        <div class="form-group">
          <label class="col-md-4 control-label">Number of Interns</label>
            <div class="col-md-4 inputGroupContainer">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                    <input name="first_name" placeholder="Number" ng-model="application.numberOfInterns" class="form-control"  type="text" >
          </div>
          </div>
        </div>

        <div class="form-group">
          <label class="col-md-4 control-label">Skill Set </label>
            <div class="col-md-4 inputGroupContainer">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                    <textarea class="form-control" name="comment" ng-model="application.skillSet" placeholder="Skill Set " ></textarea>
          </div>
          </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">University Preference</label>
            <div class="col-md-4 inputGroupContainer">
            <!-- <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                    <textarea class="form-control" name="comment" ng-model="application.skillSet" placeholder="Skill Set " ></textarea>
          </div> -->
                <div class="input-group">
                    <select ng-model="application.selectname1"
                        ng-options="item as item.name for item in universities|filter:filter2|filter:filter3" ><option value="">- select -</option>
                    </select>


                    <select ng-model="application.selectname2"
                        ng-options="item as item.name for item in universities|filter:filter1|filter:filter3" ><option value="">- select -</option>
                    </select>

                    <select ng-model="application.selectname3" ng-options="item as item.name for item in universities|filter:filter1|filter:filter2" ><option value="">- select -</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="form-group">
          <label class="col-md-4 control-label">Other Comments</label>
            <div class="col-md-4 inputGroupContainer">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                    <textarea class="form-control" name="comment" ng-model="application.comments" placeholder="Comments"></textarea>
          </div>
          </div>
        </div>


        <!-- Button -->
        <div class="form-group">
          <label class="col-md-4 control-label"></label>
          <div class="col-md-2">
            <button type="submit" class="btn btn-primary" ng-click="submitApplication()"> Submit <span class="glyphicon glyphicon-send"></span></button>
          </div>
          <div>
            <button type="submit" class="btn btn-warning" ng-click="saveApplication()"> Save <span class="glyphicon glyphicon-floppy-disk"></span></button>
          </div>

        </div>



        <!-- </fieldset> -->
        </form>
        </div>

        <div class="tabcontent" id="page2" style="display: none;">

            <table class="table">
                <thead>
                    <tr>
                        <th>Project Title</th>
                        <th>Project Description</th>
                        <th>State</th>
                        <th></th>
                    </tr>
                    <tbody>
                        <tr ng-repeat="apllication in applicationList">
                            <td>{{application.title}}</td>
                            <td>{{application.description}}</td>
                            <td>{{application.state}}</td>
                            <td><button class="btn btn-danger" ng-click="remove(application._id)" ng-show="application.state='saved'">Delete</button></td>
                            <td><button class="btn btn-warning" ng-click="edit(application._id)" ng-show="application.state='saved'">Edit</button></td>
                        </tr>
                    </tbody>
                </thead>
        </div>


        </div>



</body>

</html>

最佳答案

您的数据库得到更新,因为您已将 ng-click 指令附加到提交按钮,该指令使用 POST 正确命中您的 /applicationList 路由:这很好。

同时,您的按钮位于表单元素内,并且类型为 submit,这意味着单击它将触发表单操作。因为您已将表单操作留空 - action="" - 您也遇到了不存在的 / 路线。这就是您收到错误的原因。

一个简单的修复方法是将按钮类型更改为 button,以便它们不会触发表单操作,并从表单中删除 action 属性。

关于html - 当我尝试单击 HTML 中的提交按钮时出现 “Cannot POST/”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46086169/

相关文章:

javascript - GraphQL 和 Sequelize 不返回插入的对象

node.js - 使用 nodejs & redis & socket.io & php 的实时访问者

javascript - 如何使用 child-parentnode 将此 javascript 编码为 jquery?

java - 如何在 CData (Java) 中包装 HTML 内容以进行 XSLT - XML 到 HTML

javascript - ie11 window.location 相对路径

python - 从 HTML 文件中删除文本,但使用 python 保留 javascript 和结构

javascript - 在 AngularJS 选项卡 View 中设置默认单选/输入/复选框值

javascript - 函数返回未定义的 AngularJS

javascript - Angular 中的 ng-switch 与父子 Controller

node.js - Asterisk 11 通过 AMI 进行的主动调用事件