视频教程推荐:node js教程
十多年的海城网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。网络营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整海城建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联从事“海城网站设计”,“海城网站推广”以来,每个客户项目都认真落实执行。
最近项目需要接口传输,于是乎找了那个选择哪个语言,选择node,而且是https模式!
找了好久才解决跨域问题!废话不多说,直接上代码
let mysql = require('mysql'); let express = require('express'); let app = express(); let https = require("https"); let fs = require("fs"); // Configuare https const httpsOption = { key : fs.readFileSync("./https/3_jdong.xuexuebang.cn.key"),//https证书key cert: fs.readFileSync("./https/2_jdong.xuexuebang.cn.crt")//https证书crt } //链接数据库 let connection = mysql.createConnection({ host : '127.0.0.1', port : '3306', database : 'sz', user : 'soubei', password : 'soubei', }) connection.connect(); //解决跨域问题 app.all("*",function (req, res, next) { //允许所有请求方式 res.header("Access-Control-Allow-Origin","*");//所有 res.header("Access-Control-Allow-Headers","content-type")//post next() }) app.get('/userlist',function(req,res){ shop_name = req.query.shop_name; connection.query('SELECT * from `order` where orderStatus="暂停" ',function(error,results,fileds){ if(error) throw error; res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Headers', 'Content-type'); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH"); res.header('Access-Control-Max-Age',1728000);//预请求缓存20天 res.writeHead(200,{"Content-Type":"text/json;chartset=utf-8"}) data = [] // console.log('SELECT skuId from `cmf_order_sku` where shop_name="'+shop_name+'" group by skuId') connection.query('SELECT skuId from `cmf_order_sku` where shop_name="'+shop_name+'" group by skuId',function(error,result,fileds){ if (result !=''){ res.end(JSON.stringify(result)) } if (error == null){ res.end(JSON.stringify('请求失败')) } }) }) }) https.createServer(httpsOption, app).listen(8080,function(){ // let host = server.address().address; // let port = server.address().port; console.log("应用实例,运行在http://%s:%s") });
效果图如下
更多编程相关知识,可访问:编程教学!!
本文标题:nodejs接口如何传输数据?
标题网址:http://cdweb.net/article/cpehsg.html