广告
返回顶部
首页 > 资讯 > 前端开发 > node.js >node跨域请求方法小结
  • 697
分享到

node跨域请求方法小结

小结方法node 2022-06-04 17:06:26 697人浏览 安东尼
摘要

本文介绍了node跨域请求,主要介绍了两种方法,一种是JSONp,另一种res.wirteHead,具体如下: 第一种:jsonp 参看用nodejs实现json和jsonp服务 第二种:res.wir

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

第一种:jsonp

参看用nodejs实现json和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>

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

--结束END--

本文标题: node跨域请求方法小结

本文链接: https://www.lsjlt.com/news/12397.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作