【问题标题】:Angularjs cant send data from input to nodejs server, POST not found 404Angularjs无法将数据从输入发送到nodejs服务器,找不到POST 404
【发布时间】:2017-04-26 07:57:15
【问题描述】:

这是控制台显示的错误,我不明白为什么找不到http地址

POST http://localhost:3000/api/message 404 (Not Found)                angular.min.js
XHR finished loading: POST "http://localhost:3000/api/message".       angular.min.js
Error "Cannot POST /api/message\n"                                    controllers.js

我的控制器:

testControllers.controller('SecCtrl', ['$scope', '$http',
   function SecCtrl($scope, $http) {       
      $scope.message = '';
      $scope.saveInput = function() {              
        $http({
            method: 'POST',
            url: 'http://localhost:3000/api/message',
            headers: {'Content-Type': 'application/json'},
            data: JSON.stringify({message: $scope.message})      
        }).

        success(function(response) {
            console.log("Success " + JSON.stringify(response));
        }).

        error(function(response) {
            console.log("Error " + JSON.stringify(response));
        });
     };
}]);

server.js 代码,在我将输入数据发送到服务器后,我尝试使用 mongoose 将其保存到 mongodb:

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');

var Message = mongoose.model('Message', {
    message: String
});

mongoose.connect('mongodb://localhost:27017/test', function(err) {
    if(!err) {
        console.log('connected to mongo');
    }
});

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));

app.use(function(res,req,next) {
    res.header("Access-Control-Allow-Origin");
    res.header("Access-Control-Allow-Headers", "Content-Type,   Authorization");

    next();
})

app.get('api/message', function(req,res) {
    Message.find(function(err,message) {
        if(err) {
            res.send(err);
        } else {
            res.json(message);
        }
    })
})

app.post('api/message', function(req,res) {
    var message = new Message(req.body);
    message.save();

    res.status(200);
})

app.get('/', function(req,res) {
    res.sendFile(__dirname + '/index.html');
})

app.listen(3000);
console.log('listening on port 3000');

【问题讨论】:

    标签: angularjs node.js mongodb express mongoose


    【解决方案1】:

    我觉得应该是绝对路径/api/message:

    app.post('/api/message', function(req,res) {
        var message = new Message(req.body);
        message.save();
    
        res.status(200);
    });
    

    看这里http://expressjs.com/en/api.html#path-examples

    【讨论】:

    • 我尝试在控制器中写入相同的路径,但会导致相同的错误
    • 都是一样的,我发在主题的开头
    猜你喜欢
    • 2014-03-22
    • 1970-01-01
    • 2011-07-28
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多