简体   繁体   中英

Nodejs, Express + Angular POST 404

I am working on my MEAN stack (mySQL not MongoDB and I am also using the EJS templating engine) application and I am running into a problem with posting data into my MySQL DB. As the title says I am getting a '404' error in my console which I think indicates that the post method cannot be found. If I putt the method in the server file, the post does work but I get a message saying 'invalid json'.

Anyone has any ideas as to why this is happening?

My current code is listed as below. I am a beginner in any of this so I would really appreciate well explained answers as that is the best way to learn where it went wrong.

Server/app:

> var express = require('express'); var path = require('path'); //var
> favicon = require('serve-favicon'); var logger = require('morgan');
> var cookieParser = require('cookie-parser'); var bodyParser =
> require('body-parser'); var http = require('http');
> 
> var mysql = require('mysql');
> 
> var app = express();
> 
> var port = 1337;
> 
> // view engine setup app.set('views', path.join(__dirname, 'views'));
> app.set('view engine', 'ejs');
> 
> // uncomment after placing your favicon in /public
> //app.use(favicon(__dirname + '/public/favicon.ico'));
> app.use(logger('dev')); app.use(bodyParser.json());
> app.use(bodyParser.urlencoded({ extended: false }));
> app.use(cookieParser());
> app.use(require('stylus').middleware(path.join(__dirname, 'public')));
> app.use(express.static(path.join(__dirname, 'public')));
> app.use('/bower_components', express.static(__dirname +
> '/bower_components'));
> 
> var clientRoute = require('./routes/clientConfig.js');
> 
> new clientRoute(app);
> 
> app.use(require('./server/Dao/clientDao.js'));
> 
> module.exports = app;
> 
> app.set('port', process.env.PORT || 1337);
> http.createServer(app).listen(app.get('port'), function () {
>     console.log('Express server listening on port ' + app.get('port')); });

Angular controller:

> var clientModule = angular.module('clientModule', []);
> 
> clientModule.controller('clientController', ['$scope', '$http',
> function ($scope, $http) {
>     console.log("Hello world from controller");
>     
>     $scope.addClient = function () {
>         console.log($scope.client);
>         
>         $http.post('/createClient', $scope.client).success(function(response) {
>             console.log(response);
>         })
>     } }]);

Server-side post (I have no idea but it seems that it does not reference well to my server folder):

>  var express = require('express'); var router = express.Router(); var
> connectionProvider = require('../mysqlConnectionStringProvider.js');
> 
> router.post('/createClient', function (req, res) {
>     console.log(req.body); 
>     
>     var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
> 
>     var insertStatement = "INSERT INTO Clients SET?"
>     
>     var client = { 
>         clientName : req.body.client.clientName, // this should be req.body.client.clientName 
>         clientAddress : req.body.client.clientAddress // this should be req.body.client.clientAddress 
>     }
> 
>      
>     if (connection) {
>         connection.query(insertStatement, client, function (err, result) {
> 
>             if (err) {
>                 console.log(err);
>             }
> 
>             //console.log(result);
>         });
>     }
>     connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
> });
> 
> router.get('/createClient', function (req, res) {
>     
>     res.render('clients/createClient.ejs', {title : 'Add client'}); }) 
> 
> module.exports = router;

Html:

 <% include ../layout %> <div class="container" ng-app="clientModule" ng-controller="clientController"> <form class="navbar-form navbar-left" action="/createClient" method="post" name="formClient"> <div class="row"> <div class="form-group"> <label for="">Client name</label> <input type="text" class="form-control" placeholder="Please enter client name" name="clientName" ng-model="client.clientName" style="width: 100%" required> </div> </div> <div>&nbsp;</div> <div class="row"> <div class="form-group"> <label for="">Client address</label> <input type="text" class="form-control" placeholder="Please enter client address" name="clientName" ng-model="client.clientAddress" style="width: 100%" required> <p>{{client.clientAddress}}</p> </div> </div> <div>&nbsp;</div> <div class="row"> <div class="form-group"> <button class="btn btn-primary" ng-click="addClient()">Create client</button> </div> </div> </form> </div> <script src="./controllers/clients/clientController.js"></script> 

Thanks in advance!

To use routes from another file you can do following

routes/clientConfig.js

var express = require('express');
var router = express.Router();

router.get(...); 
router.post(...); 
router.put(...); 

module.exports = router;

server.js

...
app.use(require('./routes/clientConfig.js'));
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM