How to pass data from AngularJS frontend to Nodejs backend?

前端 未结 4 1901
滥情空心
滥情空心 2020-12-04 18:29

I have some angular js code here.




  
             


        
4条回答
  •  情深已故
    2020-12-04 19:02

    It can be the stepping stone for you to getting started:

    Index.html

    
    
    
       
       
    
        
      
    Author:

    Title:

    Body:

    Angular code app.js

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
       $scope.submit= function(){
          var data = $.param({
            book: JSON.stringify({
                author: $scope.author,
                title : $scope.title,
                body : $scope.body
            })
          });
    
          $http.post("/api/book/", data).success(function(data, status) {
            console.log('Data posted successfully');
          })
       }
    });
    

    server.js - Nodejs

    var express = require('express'); 
    var mysql = require('mysql');
    var app = express();
    
    var connection = mysql.createConnection({
         host: 'localhost',
         user: '',
         password: '',
         database: 'copedb'
    });
    connection.connect();
    
    app.post('/api/book', function(req, res, next){
       var cope = req.body.params;
       var query = connection.query('insert into cope set ?', cope, function(err, result) {
         if (err) {
           console.error(err);
           return res.send(err);
         } else {
           return res.send('Ok');
         }
    });
    app.listen(8080);
    

提交回复
热议问题