zoukankan      html  css  js  c++  java
  • 用原生node实现服务器上的MySQL数据库传送给前端ajax接口接收

    node代码实现

    ```node var http = require("http"); var fs = require("fs"); var url = require("url"); var mysql = require("mysql");

    http.createServer(function(request, response) {

    var connection = mysql.createConnection({
    host : "localhost",
    post : 3000,
    user : "",
    password : "
    ",
    database : "123"
    });

    var pathname = url.parse(request.url).pathname;
    var ext = pathname.match(/(.[^.]+|)$/)[0]; //取得后缀名
    switch (ext) {
    case ".css":
    case ".js":
    case ".png":
    case ".jpg":
    fs.readFile("." + request.url, function(err, data) {
    response.writeHead(200, {
    "Content-Type": {
    ".css": "text/css",
    ".js": "application/javascript",
    ".jpg": "image/jpeg",
    ".png": "image/png",
    }[ext]
    });
    response.end(data);
    });
    break;
    default:
    if(request.url == "/login"){
    connection.query("SELECT * FROM login", function(error, results) {
    if(error) {
    console.log("login error");
    } else {
    var loginobj = {
    success : true,
    information : results
    };
    response.end(JSON.stringify(loginobj));
    }
    });
    }
    else if(request.url == "/lotteryPeople") {
    connection.query("SELECT * FROM lotteryPeople", function(error, results)
    {
    if(error) {
    console.log("lottey error");
    } else {
    var lotteryPeopleobj = {
    success : true,
    lotteryP : results
    };
    response.end(JSON.stringify(lotteryPeopleobj));
    }
    });
    }
    else {
    fs.readFile("./index.html", "utf-8", function(err,data) {
    if (err) throw err;
    //response.write();
    response.writeHead(200, {
    "Content-Type": "text/html",
    });
    response.end(data);
    });
    }
    }
    //connection.end();
    }) .listen(3000);
    console.log("server start...");

    <div style="font-size:14px">注释:创建用户给权限从服务器的123数据库上取得login和lotteryPeople两张表上的数据返回给前端,这里我只实现了从服务器取数据给前端ajax接口接收,在前端ajax接口接收url分别写"http://xxx:3000/login"和"http://xxx:3000/lotteryPeople"即可。</div>
  • 相关阅读:
    linux 重新设置mysql密码
    php 一些个 常用 函数
    nginx php错误日志开启
    linux crontab 定时执行任务(php)
    聚合短信接口-- php
    Commons Collections1分析
    spring之 注解ioc&依赖注入 & spring整合mybatis
    Spring之 IOC&依赖注入
    java之 Mybatis(二)
    java之 MyBatis(一)
  • 原文地址:https://www.cnblogs.com/fyjreact/p/11005709.html
Copyright © 2011-2022 走看看