如何在Angular / Node.js / Express中将客户端参数传递给服务器端

时间:2022-03-01 16:09:06

Probably a very basic question, but I cannot seem to find a simple answer.

可能是一个非常基本的问题,但我似乎无法找到一个简单的答案。

I have a GET method leveraging Angular's $http that is requesting a promise from a particular url (URL_OF_INTEREST).

我有一个GET方法利用Angular的$ http请求来自特定网址的承诺(URL_OF_INTEREST)。

On this server, I run an express script server.js script that can handle GET requests.

在此服务器上,我运行一个可以处理GET请求的快速脚本server.js脚本。

server.js

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var stripe     = require("stripe")("CUSTOM_TEST_TOKEN");

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        
var router = express.Router();              // get an instance of the express Router

router.get('/', function(req, res, next) {

    var stripeToken = "CUSTOM_PAYMENT_TOKEN";

    var charge = stripe.charges.create({
        amount: 1100, // amount in cents, again
        currency: "usd",
        source: stripeToken,
        description: "Example charge"
    }, function(err, charge) {
        if (err && err.type === 'StripeCardError') {
            res.json(err);   
        } else {
            res.json(charge);   
        }
    });
});

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    next();
})

app.use('/api', router); // register our route
app.listen(port); // start our server
console.log('Magic happens on port ' + port);

I can communicate with the URL_OF_INTEREST using an Angular GET method as follows:

我可以使用Angular GET方法与URL_OF_INTEREST进行通信,如下所示:

$http.get('URL_OF_INTEREST')
        .success(
            function(success){
                console.log(success)
            })
        .error(
            function(error){
                console.log(error)
            });

However, the fields amount, currency, source and description need to be ideally passed on from the Angular client side application.

但是,字段数量,货币,来源和描述需要从Angular客户端应用程序中理想地传递。

How can this be achieved and how can my express application read this data?

如何实现这一点以及我的快速应用程序如何读取此数据?

4 个解决方案

#1


6  

You need to pass the data in your get call as folow:

您需要在get call中传递数据,如下所示:

var data = {
    amount: 3,
    currency: 2,
    source: 3,
    description: 4
};

$http.get('URL_OF_INTEREST', data) // PASS THE DATA AS THE SECOND PARAMETER
    .success(
        function(success){
            console.log(success)
        })
    .error(
        function(error){
            console.log(error)
        });

And in your backend, you can get your url parameters as folow:

在你的后端,你可以获得你的url参数如下:

router.get('/', function(req, res, next) {

    var amount = req.query.amount; // GET THE AMOUNT FROM THE GET REQUEST

    var stripeToken = "CUSTOM_PAYMENT_TOKEN";

    var charge = stripe.charges.create({
        amount: 1100, // amount in cents, again
        currency: "usd",
        source: stripeToken,
        description: "Example charge"
    }, function(err, charge) {
        if (err && err.type === 'StripeCardError') {
            res.json(err);   
        } else {
            res.json(charge);   
        }
    });
});

#2


6  

HTTP GET method

HTTP GET方法

Client:

$http.get('/login', {params: {name: 'ABCXYZ'}})
    .success(
        function(success){
            console.log(success)
        })
    .error(
        function(error){
            console.log(error)
        });

Server:

router.get('/login', function(req, res, next) {
    var username = req.query.name;
    res.json({'status': 200, 'msg': 'success'});
}

HTTP POST method

HTTP POST方法

Client:

$http.post('/login', {params: {name: 'ABCXYZ'}})
    .success(
        function(success){
            console.log(success)
        })
    .error(
        function(error){
            console.log(error)
        });

Server:

router.post('/login', function(req, res, next) {
    var username = req.body.params.name;
    res.json({'status': 200, 'msg': 'success'});
}

#3


3  

Answer vs Good Solution

回答与好的解决方案

  • HTTP POST is preferred while sending data to the server.

    在将数据发送到服务器时,首选HTTP POST。

  • HTTP GET method means querying for data, not sending data. Because of that, an HTTP request with GET method will always have request.body empty. But still data can be sent to server via GET using query string. In your case:

    HTTP GET方法意味着查询数据,而不是发送数据。因此,使用GET方法的HTTP请求将始终为request.body为空。但是仍然可以使用查询字符串通过GET将数据发送到服务器。在你的情况下:

Client

$http.get('url_to_be_hit', { name : 'Mr. X'})
    .success(function(res){ //response })
    .error(function(err){ //failure });

Server

app.get('/url_to_be_hit', function(req,res,next){
   //req.query.name
}); 

Happy Helping!

#4


1  

You can create a JS object with your parameters, and then use jQuery's $.param (http://api.jquery.com/jquery.param/) to easily serialize them into a URL query string:

您可以使用您的参数创建一个JS对象,然后使用jQuery的$ .param(http://api.jquery.com/jquery.param/)轻松地将它们序列化为URL查询字符串:

var parameters = {
   amount: 123,
   description: 'test'
};

And on your $http call:

并在您的$ http电话:

$http.get('URL_OF_INTEREST'+'?'+$.param(parameters))
        .success(
            function(success){
                console.log(success)
            })
        .error(
            function(error){
                console.log(error)
            });

EDIT: OR if you don't want to use jQuery:

编辑:或者,如果你不想使用jQuery:

$http.get('URL_OF_INTEREST', { params: parameters })
        .success(
            function(success){
                console.log(success)
            })
        .error(
            function(error){
                console.log(error)
            });

On server-side, just use the req object to get the parameters:

在服务器端,只需使用req对象来获取参数:

var amount = req.query.amount;
var description = req.query.description;

#1


6  

You need to pass the data in your get call as folow:

您需要在get call中传递数据,如下所示:

var data = {
    amount: 3,
    currency: 2,
    source: 3,
    description: 4
};

$http.get('URL_OF_INTEREST', data) // PASS THE DATA AS THE SECOND PARAMETER
    .success(
        function(success){
            console.log(success)
        })
    .error(
        function(error){
            console.log(error)
        });

And in your backend, you can get your url parameters as folow:

在你的后端,你可以获得你的url参数如下:

router.get('/', function(req, res, next) {

    var amount = req.query.amount; // GET THE AMOUNT FROM THE GET REQUEST

    var stripeToken = "CUSTOM_PAYMENT_TOKEN";

    var charge = stripe.charges.create({
        amount: 1100, // amount in cents, again
        currency: "usd",
        source: stripeToken,
        description: "Example charge"
    }, function(err, charge) {
        if (err && err.type === 'StripeCardError') {
            res.json(err);   
        } else {
            res.json(charge);   
        }
    });
});

#2


6  

HTTP GET method

HTTP GET方法

Client:

$http.get('/login', {params: {name: 'ABCXYZ'}})
    .success(
        function(success){
            console.log(success)
        })
    .error(
        function(error){
            console.log(error)
        });

Server:

router.get('/login', function(req, res, next) {
    var username = req.query.name;
    res.json({'status': 200, 'msg': 'success'});
}

HTTP POST method

HTTP POST方法

Client:

$http.post('/login', {params: {name: 'ABCXYZ'}})
    .success(
        function(success){
            console.log(success)
        })
    .error(
        function(error){
            console.log(error)
        });

Server:

router.post('/login', function(req, res, next) {
    var username = req.body.params.name;
    res.json({'status': 200, 'msg': 'success'});
}

#3


3  

Answer vs Good Solution

回答与好的解决方案

  • HTTP POST is preferred while sending data to the server.

    在将数据发送到服务器时,首选HTTP POST。

  • HTTP GET method means querying for data, not sending data. Because of that, an HTTP request with GET method will always have request.body empty. But still data can be sent to server via GET using query string. In your case:

    HTTP GET方法意味着查询数据,而不是发送数据。因此,使用GET方法的HTTP请求将始终为request.body为空。但是仍然可以使用查询字符串通过GET将数据发送到服务器。在你的情况下:

Client

$http.get('url_to_be_hit', { name : 'Mr. X'})
    .success(function(res){ //response })
    .error(function(err){ //failure });

Server

app.get('/url_to_be_hit', function(req,res,next){
   //req.query.name
}); 

Happy Helping!

#4


1  

You can create a JS object with your parameters, and then use jQuery's $.param (http://api.jquery.com/jquery.param/) to easily serialize them into a URL query string:

您可以使用您的参数创建一个JS对象,然后使用jQuery的$ .param(http://api.jquery.com/jquery.param/)轻松地将它们序列化为URL查询字符串:

var parameters = {
   amount: 123,
   description: 'test'
};

And on your $http call:

并在您的$ http电话:

$http.get('URL_OF_INTEREST'+'?'+$.param(parameters))
        .success(
            function(success){
                console.log(success)
            })
        .error(
            function(error){
                console.log(error)
            });

EDIT: OR if you don't want to use jQuery:

编辑:或者,如果你不想使用jQuery:

$http.get('URL_OF_INTEREST', { params: parameters })
        .success(
            function(success){
                console.log(success)
            })
        .error(
            function(error){
                console.log(error)
            });

On server-side, just use the req object to get the parameters:

在服务器端,只需使用req对象来获取参数:

var amount = req.query.amount;
var description = req.query.description;