jsonp nodejs跨域传输

Nodejs端代码:

这里是我整个的后端代码,前端只请求了一个 prodess_get,所以只要看那一部分代码即可。

var express = require('express');
var urlLib = require('url');
var app = express();
 
app.use('/public', express.static('public'));
 
app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})
app.get('/login.html', function (req, res) {
   res.sendFile( __dirname + "/" + "login.html" );
})
app.get('/register.html', function (req, res) {
   res.sendFile( __dirname + "/" + "register.html" );
})
//数据库访问
app.get('/mysqlget', function (req, res) {

})
//登录
app.get('/login_get', function (req, res) {
	console.log('--------------------------visit mysql----------------------------');
	var mysql  = require('mysql');  
	 
	var connection = mysql.createConnection({     
	  host     : 'localhost',       
	  user     : 'root',              
	  password : '123456',       
	  port: '3306',                   
	  database: 'test' 
	}); 
	 
	connection.connect();
	var  sql = 'SELECT * FROM user where name = ? and pass = ?';
	var  addSqlParams = [req.query.first_name, req.query.last_name];

	//查
	connection.query(sql,addSqlParams,function (err, result) {
	        if(err){
	          console.log('[SELECT ERROR] - ',err.message);
	          return;
	        }
	 if(result.length > 0){
		 console.log('{ msg: "用户 "' + req.query.first_name + '"登陆成功" }');

		 res.sendFile( __dirname + "/" + "index.html" );
	 }else{
		 console.log('{ msg: "用户 "' + req.query.first_name + '"登陆失败" }');
	 }
	});


	connection.end();

})
//账号注册
app.get('/register_get', function (req, res) {
	var mysql  = require('mysql');  
	 
	var connection = mysql.createConnection({     
	  host     : 'localhost',       
	  user     : 'root',              
	  password : '123456',       
	  port: '3306',                   
	  database: 'test' 
	}); 
	 
	connection.connect();
	var  addSql = 'INSERT INTO user(name,pass) VALUES(?,?)';
	var  addSqlParams = [req.query.first_name, req.query.last_name];
	//增
	connection.query(addSql,addSqlParams,function (err, result) {
	        if(err){
		         console.log('[INSERT ERROR] - ',err.message);
		         console.log('插入数据失败');
		         return;
	        }else{
	        	console.log('插入数据成功!');
	        }        
	 
	       console.log('--------------------------INSERT----------------------------');
	       //console.log('INSERT ID:',result.insertId);        
	       console.log('INSERT ID:',result);        
	       console.log('-----------------------------------------------------------------\n\n');  
	});
	connection.end();
})
app.get('/process_get', function (req, res) {
	
	console.log('--------------------------process_get----------------------------');
	var mysql  = require('mysql');  
	 
	var connection = mysql.createConnection({     
	  host     : 'localhost',       
	  user     : 'root',              
	  password : '123456',       
	  port: '3306',                   
	  database: 'test' 
	}); 
	 
	connection.connect();
	var  sql = 'SELECT * FROM user';
	//var  addSqlParams = [req.query.name, req.query.pass];

	//查
	connection.query(sql,function (err, result) {
	        if(err){
	          console.log('[SELECT ERROR] - ',err.message);
	          return;
	        }
	        var response = {
	        "first_name":"diyunlong",
	        "last_name":"jdkal;fld"
		    };
	        var parms = urlLib.parse(req.url,true);
	        console.log(parms);
	        console.log(result);
	        strResult =JSON.stringify(result);
	        console.log(strResult);
	        res.jsonp(strResult);
	         
	       // res.end(res.json(strResult));
	       /* var strResult = {code:201,message:"执行失败额,玮哥哥"};
	        strResult = JSON.stringify(strResult);
	        res.json(strResult);*/
	});


	connection.end();
	
 
   // 输出 JSON 格式
   /*var response = {
       "first_name":req.query.first_name,
       "last_name":req.query.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));*/
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
 
})

前端代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>登录</title>
		<script src="js/jquery-3.3.1.min.js"></script>
	</head>
	<body>
		<p>登录</p>
		<form action="http://127.0.0.1:8081/process_get" method="GET">
			First Name: <input id="name" type="text" name="first_name">  <br>
			 
			Last Name: <input id="pass" type="text" name="last_name">  <br />
			<input type="submit" value="Submit">
			
		</form>
		<button id="submit_btn"> 提 交 </button>
	</body>
	<script>
		function submitclick(){
			var name1 = document.getElementById("name").value;
			var pass1 = document.getElementById("pass").value;
			$.ajax({			
				async:true,	
				cache:false,		
				url: 'http://127.0.0.1:8081/process_get',			
				type: 'get',			
				dataType: 'jsonp',
				timeout: 5000,			 
				contentType: 'application/json; charset=utf-8',
				success:function(result){			
//					alert("succ")		
					var datas = JSON.parse(result);
					console.log(datas[0].name)

					
				},			  
				error:function(res){	
					console.log(res);
					alert("res")			
				}			
			});


		}
		document.getElementById("submit_btn").onclick = submitclick;

	</script>
</html>

这里推荐去看一篇文章:https://www.jianshu.com/p/3179631bd7bd

还有一篇:https://blog.csdn.net/dai_jing/article/details/46564627

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不染心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值