【简】Node.js实现简单数据返回!!!

1.安装node.js (https://www.baidu.com/link?url=Zc5ZhRCz3mtjk2Vep48iK_fxhnqCquTpeWWI8WVxX-W&wd=&eqid=b67924fd00087041000000065e0db1c4)

2.初始化,并安装依赖包 npm init  && npm install

3创建文件例:app.js

  

var mysql = require('mysql');
var http = require('http');
var connection = mysql.createConnection({
    host: '192.168.0.43',
    user: 'root',
    port: '30030',
    password: 'AbcXyz123',
    database: 'cpqueuedb'
});
connection.connect();

var sql = 'SELECT * FROM queueyyinfo';
//查
connection.query(sql, function(err, result) {
    if (err) {
        console.log('[SELECT ERROR] - ', err.message);
        return;
    }
    http.createServer(function(request, response) {
        response.writeHead(200, {
            "Content-Type": 'text/plain',
            'charset': 'utf-8',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
        });
        response.end(JSON.stringify(result))
    }).listen(3030)
    connection.end();
});


console.log("http://127.0.0.1:3030/");

然后运行 node app.js

然后创建html 利用ajax来调用测试。这里偷个懒使用了jq

<!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>

</body>

</html>
<script src="https://cdn.bootcss.com/jquery/1.11.2/jquery.js"></script>
<script>
    $.ajax({
        url: 'http://127.0.0.1:3030/',
        type: 'get',
        success: function(data) {
            console.log(JSON.parse(data))
        },
        error: function(err) {
            console.log(err)
        }
    })
</script>
发布了20 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/tt22761/article/details/103807577
今日推荐