AngularJS POST and GET 404 Error

2019-09-10 11:03发布

问题:

Using AngularJS, I'm trying to post data from a form into an ng-repeat and save to a database. When I click submit, I get the 404 error for post and get. Can someone help show me where I went wrong?

Here's my html:

<html ng-app="Inventory-App">
  <head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js" charset="utf-8"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

    <!-- SEMANTIC -->
    <link rel="stylesheet" type="text/css" href="../semantic/dist/semantic.min.css">
    <script src="../semantic/dist/semantic.min.js"></script>

    <!-- MY STUFF -->
    <link rel="stylesheet" href="../css/styles.css" media="screen" title="no title" charset="utf-8">
    <script src="../scripts/script.js" charset="utf-8"></script>
    <script src="../scripts/services/itemsAPI.js" charset="utf-8"></script>
    <script src="../scripts/controllers/main.js" charset="utf-8"></script>
    <script src="../scripts/app.js" charset="utf-8"></script>

  </head>
  <body ng-controller="MainController">
    <nav>
      <h1>Cabinet.me</h1>
      <p>An Inventory of Your Kitchen</p>
    </nav>
    <div class="ui container">
      <form class="ui form">
        <div class="field">
          <label>Item</label>
          <input type="text" placeholder="Item" ng-model="post.name">
        </div>
        <div class="field">
          <label>Details (if any)</label>
          <input type="text" placeholder="Details" ng-model="post.details">
        </div>
        <div class="field">
          <label>Amount</label>
          <select class="ui dropdown" ng-model="post.amount">
            <option value="">Amount</option>
            <option value="1">High</option>
            <option value="1">Medium</option>
            <option value="0">Low</option>
          </select>
        </div>
        <button class="ui button" type="submit" ng-click="createItem(post)">Submit</button>
      </form>
      <div class="ui divider"></div>

      <div class="ui cards">
        <div class="card" ng-repeat="item in items | orderBy: 'created_at':true">
          <div class="content">
            <div class="header">{{item.name}}</div>
            <div class="meta">Availability: {{item.amount}}</div>
            <div class="description">
              {{item.details}}
            </div>
            <button class="ui secondary button">
              Delete
            </button>
          </div>
        </div>


      </div>

    </div>
  </body>
</html>

Here's my Controller:

angular
  .module('mainController', ['itemsAPI'])
  .controller('MainController', ['$scope', '$http', 'itemsAPI',
    function( $scope, $http, itemsAPI ) {

      $scope.items = [];
      // $scope.itemData = '';

      $scope.createItem = function(post){
        var newItem = {
          item : {
            name: post.name,
            details: post.details,
            amount: post.amount
          }
        }

        itemsAPI.create(newItem).then(function(response){
          console.log(response);
          $scope.items.push(response.data);
        })

        itemsAPI.getAll().then(function(response){
          $scope.items = response.data;
        });

      }

      $scope.removeItem = function(item){

        itemsAPI.remove(item._id).then(function(response){
          if (response.status == 203) {
            $scope.items = $scope.items.filter(function(i){
              return i._id != item._id;
            });
          }
        });
      }

    }]);

Here's the itemsAPI code:

angular
  .module('itemsAPI', [])
  .factory('itemsAPI', ['$http',
    function($http) {
      return {
        getAll: function(){
          return $http.get('/items');
        },

        create: function(newItem){
          return $http.post('/items', newItem);
        },

        remove: function(id){
          return $http.delete('/items/' + id);
        }

      }
    }])

And my API route:

var express = require('express');
var router = express.Router();
var Item = require('../../models/item');

// Get
router.get('/', function(req, res, next) {
  Item.find(function(err, items) {
    if (err) {
      next(err);
    }else {
      res.json(items);
    }
  })
});

router.post('/', function(req, res, next) {
  Item.create(req.body.item, function(err, item) {
    if (err) {
      next(err);
    }else {
      res.json(item);
    }
  });
});

router.delete('/:id', function(req, res, next) {
  Item.findByIdAndRemove(req.params.id, function(err) {
    if (err) {
      next(err);
    }else {
      res.status(203).end();
    }
  })
});

module.exports = router;

I appreciate any help I can get!

回答1:

Replace this

router.post('/', function(req, res){

with

router.post('/items', function(req, res){

in inventory/server/routes/api/items.js

Edit:

I'm mistaken. You use '/api/items' route in app.js and not necessary to add 'items' path as I wrote above. But on the client side you try to post your data on the '/items' route not on '/api/items'.