• node+express 发送get请求


    var express = require('express')
      , app = express();
    
    
    var querystring = require('querystring');
    var util = require('util');
    //和数据库建立连接
    var mysql  = require('mysql');  
    var connection = mysql.createConnection({     
      host     : 'localhost',       
      user     : 'root',              
      password : '123456',       
      // port: '3306',                   
      database: 'test', 
    }); 
     
    connection.connect(); 
    
    //解决跨域
    app.all('*',function (req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
      res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
      if (req.method == 'OPTIONS') {
        res.send(200);
      }
      else {
        next();
      }
    });
    
    
    // 获取列表
    app.get('/list', function (req, res) {
      let [addSql,addSqlParams] = ['',[]]
      if(req.query.type == undefined){
        addSql = 'SELECT * FROM list WHERE userId=?';
        addSqlParams = [req.query.userId]
      }else{
        addSql = 'SELECT * FROM list WHERE userId=? and type=?';
        addSqlParams = [req.query.userId,req.query.type]
      }
      connection.query(addSql,addSqlParams,function (err, result) {
        if(err){
          console.log('[INSERT ERROR] - ',err.message);
          return;
        } 
        if(result.length){
          let params = {
            code:1,
            message:"成功",
            data:result
          }     
          res.send(params)
        }else{
          let params = {
            code:0,
            message:"暂无数据"
          }     
          res.send(params)
        }     
      });
    });
    
    var server = app.listen(8081, function () {
     
      var host = server.address().address
      var port = server.address().port
     
      console.log("应用实例,访问地址为 http://%s:%s", host, port)
     
    })
    

      

  • 相关阅读:
    Boolean()类型转换
    ECMAscript 变量作用域
    jQuery 添加样式属性的优先级别
    css类选择器类名覆盖优先级
    巡风扫描器安装-windows部署
    atom无法安装插件的解决方法之一
    网络爬虫url跳转代码
    查看天气的代码
    三级地名菜单
    购物清单代码
  • 原文地址:https://www.cnblogs.com/linsx/p/9882050.html
Copyright © 2020-2023  润新知