Ошибка состояния сервера Express 404 с AngularJS $ http.post

0

Поэтому я устанавливаю отдельные порты для своего экспресс-сервера и моего углового переднего конца, используя йоман и хрюкаю в первый раз. Это также моя первая попытка веб-проекта с этой структурой клиент/сервер, и я ударил стену.

У меня есть форма регистрации в моем лицевом конце под localhost: 9000/signup, и когда я нажимаю submit, я получаю следующую обратную

{firstname: "test", lastname: "test", email: "test", password1: "test", password2: "test"}
angular.js:12759 POST http://localhost:9000/signup 404 (Not Found)

(anonymous) @ angular.js:12759
sendReq @ angular.js:12492
serverRequest @ angular.js:12244
processQueue @ angular.js:17051
(anonymous) @ angular.js:17095
$digest @ angular.js:18233
$apply @ angular.js:18531
(anonymous) @ angular.js:27346
dispatch @ jquery.js:5206
elemData.handle @ jquery.js:5014
angular.js:14700 Possibly unhandled rejection: {"data":"Cannot POST     /signup\n","status":404,"config":
{"method":"POST","transformRequest":        
[null],"transformResponse:[null],"jsonpCallbackParam":"callback","url":"/signup","data":
{"firstname":"test","lastname":"test","email":"test","password1":"test",
"password2":"test"},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}}
,"statusText":"Not Found","xhrStatus":"complete"}

В первой строке я печатаю результаты формы обратно в консоль браузеров. Во-вторых, 404 on/signup, и я не уверен, что это экспресс-маршрут или клиент/регистрация?

Вот мой signup.js, который находится в папке /routes в экспресс

// Include Express
var express = require('express');
// Initialize the Router
var router = express.Router();

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

// show the request body in the command line
console.log(req.body);

// return a json response to angular
res.json({
    'msg': 'success!'
});
});

// Expose the module
module.exports = router;

И я включил его в свой файл app.js в экспресс с

var signup = require('./routes/signup');
...
app.use('/signup', signup);

Абд, наконец, моя папка signup.js, которая является контроллером для формы/регистрации.

'use strict';

angular.module('clientApp') // make sure this is set to whatever it is in your client/scripts/app.js
  .controller('SignupCtrl', function ($scope, $http) { // note the added $http depedency

    // Here we're creating some local references
    // so that we don't have to type $scope every
    // damn time
    var user,
        signup;

    // Here we're creating a scope for our Signup page.
    // This will hold our data and methods for this page.
    $scope.signup = signup = {};

    // In our signup.html, we'll be using the ng-model
    // attribute to populate this object.
    signup.user = user = {};

    // This is our method that will post to our server.
    signup.submit = function () {

      // make sure all fields are filled out...
      // aren't you glad you're not typing out
      // $scope.signup.user.firstname everytime now??
      if (
        !user.firstname ||
        !user.lastname ||
        !user.email ||
        !user.password1 ||
        !user.password2
      ) {
        alert('Please fill out all form fields.');
        return false;
      }

      // make sure the passwords match match
      if (user.password1 !== user.password2) {
        alert('Your passwords must match.');
        return false;
      }

      // Just so we can confirm that the bindings are working
      console.log(user);


    $http.post('/signup', user)
    .then(function(response) {
      console.log(response.data);
  });
}
  });

Я официально преуменьшен и буду любить некоторое понимание - любая помощь очень ценится.

  • 0
    на каком порту работает экспресс?
Теги:
express

1 ответ

1
Лучший ответ

Проблема в том, что вы отправляете на localhost: 9000/signup, что является интерфейсом, но интерфейс не поддерживает почтовый метод для этого маршрута. Вам нужно отправить запрос на localhost: {YOUR_EXPRESS_SERVER_PORT}/регистрация.

Измените этот $http.post('/signup', user) на $http.post('http://localhost:{YOUR_EXPRESS_SERVER_PORT}/signup', user)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню