以下是控制台中显示的错误,我无法理解为什么找不到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
my controllerjs:
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');
答案 0 :(得分:1)
我认为它应该是绝对路径/api/message
:
app.post('/api/message', function(req,res) {
var message = new Message(req.body);
message.save();
res.status(200);
});