当前位置: 移动技术网 > IT编程>开发语言>JavaScript > node跨域请求方法小结

node跨域请求方法小结

2017年12月12日  | 移动技术网IT编程  | 我要评论

维修电视,靠靠墙,bt5中文版下载

本文介绍了node跨域请求,主要介绍了两种方法,一种是jsonp,另一种res.wirtehead,具体如下:

第一种:jsonp

参看用

第二种:res.wirtehead

node部分

var http = require('http')
var url = require('url')
var querystring = require('querystring')

var port = 9000
var jsondata = { 'name': 'xiaohong', 'job': 'daboss' }
http.createserver(function (req, res) {
  // var pathstr = url.parse(req.url)
    res.writehead(200, {
    'content-type': 'application/json;charset=utf-8',
    'access-control-allow-credentials': true,
    'access-control-allow-origin': '*'
  })
  var type = req.method;
  if (type == 'get') {
   
    res.end(json.stringify(jsondata))
  } else if (type == 'post') {
    var str = '';
    req.on('data',function(chunk){
      str += chunk;
    })
    
    req.on('end',function(){
      var data = querystring.parse(str)
      console.log(data)
      if(data.name == "" || data.job == ""){
        res.end(json.stringify({'success':true,msg:'填写有误'}))
      }else{
        res.end(json.stringify({'success':false,msg:'添加成功'}))
      }

    })
  }

}).listen(port, function () {
  console.log('server is runing at port ' + port)
})

重点部分是添加响应头信息

  res.writehead(200, {
    'content-type': 'application/json;charset=utf-8',
    'access-control-allow-credentials': true,
    'access-control-allow-origin': '*' //可以是*,也可以是跨域的地址
  })

ajax里不需要做任何特殊处理

datatype仍旧是json

html部分

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>document</title>
</head>
<body>
  <a class="click" href="javascript:get_jsonp()" rel="external nofollow" >click me</a>
  <p class="result"></p>
  <label>姓名:</label>
  <input class="name" type="text" />
  <label>职位:</label>
  <input class="job" type="text">
  <a class="add" href = "javascript:add()">添加</a>
  <p class="msg"></p>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
    function get_jsonp() {
      $.ajax({
        type: 'get',
        datatype: 'json',
        url: 'http://localhost:9000',
        success: function (data) {
          $('.result').html('my name is ' + data.name)
        },
        error: function (err) {
          $('.result').html('出错了 ' + err.status)
        }
      })
    }
    function add(){
      $.ajax({
        type:'post',
        url:'http://localhost:9000',
        datatype:'json',
        data:{
          'name':$(".name").val(),
          'job':$(".job").val()
        },
        success:function(data){
          $('.msg').html(data.msg)
        },
        error:function(err){
          
           $('.msg').html('出错了'+err.status)
        }
      })
    }
  </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网