nodejs接口如何传输数据?


本文摘自PHP中文网,作者青灯夜游,侵删。

视频教程推荐:node js教程

最近项目需要接口传输,于是乎找了那个选择哪个语言,选择node,而且是https模式!
找了好久才解决跨域问题!废话不多说,直接上代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

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")

});

效果图如下

阅读剩余部分

相关阅读 >>

javascript中promise.all和promise.race方法的介绍(附代码)

一文搞懂node.js中的事件循环

浅谈node.js中require()的工作原理

使用node.js “debug”模块避免日志污染应用程序日志

nodejs http请求相关的总结介绍

浅谈 node.js 中间件的工作原理

深入浅析node.js中的异步

node.js中怎么进行调试?

exports和module.expors之间有什么区别及联系?

为什么node.js要引入buffer?浅析缓冲区buffer

更多相关阅读请进入《node.js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...