Node.js return JSON

When using JQuery Ajax request data from the server or sending data to the server often encounter errors, common solution is to use a cross-domain JSONP request can not be in Ajax. For security reasons, there will be a browser-origin policy, but <script /> tag but have the ability to access data across domains, and this is the basic principle JSONP work. About the same-origin policy and what is JSONP, the garden can refer to this article http://www.cnblogs.com/yuzhongwusan/archive/2012/12/11/2812849.html

  In implementing JSONP Node.js is very simple, we go back and run a JavaScript function from the server through the following code, the JavaScript function has been defined well in advance the caller, so when it is returned automatically executed.

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

router.get('/getinfo', function(req, res, next) {
  var _callback = req.query.callback;
  var _data = { email: '[email protected]', name: 'jaxu' };
  if (_callback){
      res.type('text/javascript');
      res.send(_callback + '(' + JSON.stringify(_data) + ')');
  }
  else{
      res.json(_data);
  }
});

module.exports = router;

The code must return a predetermined type of data from a server, the code res.type ( 'text / javascript') is applied before the returned data is used to tell the browser which is a piece of JavaScript code.

  JQuery front page by calling:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jsonp test</title>
    <script src="/bower_components/jquery/dist/jquery.js"></script>
</head>
<body>
    <input type="button" value="click" id="btn">
    <script type="text/javascript">
        $(function(){
            $('#btn').on('click', function(){
                $.get('http://anothersite/api/getinfo', function(d){
                    console.log(d);
                } 'Jsonp' );
            });
        });
    </script>
</body>
</html>

Of course, if express, it is possible to directly use the following code:

router.get('/getinfo',function  (req,res,next) {
    var _data = { email: '[email protected]', name: 'jaxu' };
    res.type('application/json');
    res.jsonp(_data);
});

 

Guess you like

Origin www.cnblogs.com/qqhfeng/p/11869452.html