简体   繁体   English

在Node.js中更改为其他页面/组件时,如何运行其他SQL函数(反应)?

[英]How to run a different SQL function when changing to a different page/component in Node.js (React)?

First and foremost, I managed to extract the information from SQL using the mssql module along with node.js, express and axios. 首先,我设法使用mssql模块以及node.js,express和axios从SQL中提取信息。 (server.js) (server.js)

It works fine when I run both development servers (React:3000, node:5000). 当我同时运行两个开发服务器(反应:3000,节点:5000)时,它工作正常。

Here's the code for server.js 这是server.js的代码

const express = require('express');
var cors = require('cors')
const app = express();

app.use(cors())
app.enable('trust proxy');

app.get('/', function (req, res) {

    const sql = require("mssql");

    //DB configuration object
    const config = {
        user: 'INSERT USERNAME HERE',
        password: 'INSERT PASSWORD HERE',
        server: 'INSERT SERVER NAME HERE',  
        database: 'INSERT DB NAME HERE' 
    };

    //connnecting to DB
    sql.connect(config, function (err) {

        if (err) console.log(err);
         //if (err) console.log(err);

        //creates Request object
        const request = new sql.Request();

       //search query string
       const queryString = "INSERT QUERY HERE"

        //query to DB and gets data
        request.query(queryString, function (err, recordset) {

            //to log user ip address (nothing particular)
            console.dir(req.ip)

            if (err) console.log(err)

            // send records as a response
            res.send(recordset);
            sql.close();
        });
    });
});

const server = app.listen(5000,function () {
    console.log('Server is running..');
});

My question is how do I make the queryString dynamic when I change to a different page or component? 我的问题是,当我切换到其他页面或组件时,如何使queryString动态?

Here's the original table component where I put the information into. 这是我将信息放入其中的原始表格组件。

import Page from 'components/Page';
import React from 'react';
import { Card, CardBody, CardHeader, Col, Row } from 'reactstrap';
import Result from 'components/Result';
import API from '../routes/api/api';

class TablePage extends React.Component {
  constructor(props){
    super(props);
    this.state = {
            userList: null
    };
  }
  render() { 

    const { userList } = this.state;
    const tableTypes = ['Report'];
    var today = new Date();
    today.setDate(today.getDate() -8);
    var today2 = new Date().toISOString().slice(0, 10)
    var dd = today.getDate();
    var mm = today.getMonth()+1;
    var yyyy = today.getFullYear();

    if(dd<10) {
    dd = '0'+dd
      } 
    if(mm<10) {
    mm = '0'+mm
     }   
     today = yyyy + '-' + mm + '-' + dd;

    return (
      <Page
        title={"Completed RFQs" + " " + today + "~" + today2}
        breadcrumbs={[{ name: 'report', active: true }]}
        className="TablePage"
      >
        {tableTypes.map((tableType, index) => (
          <Row key={index}>
            <Col>
              <Card className="mb-3">
                <CardHeader>{tableType || 'default'}</CardHeader>
                <CardBody>
                  <Result  userList={userList} />
                </CardBody>
              </Card>
            </Col>
          </Row>
        ))}
      </Page>
    );

  }

  async componentDidMount() {
          try{
        let userData = await API.get('/')
         .then(res => res.data);

         const users = [];
         for (var i in userData.recordsets) {
          for (var j in userData.recordsets[i]) {   
             var x = userData.recordsets[i][j];
             users.push(x)
          }
    }//end for loop 

const userList = users.map((user,index)=>
  <tr key={index}>
  <th scope = "row">{(i++)+1}</th>
  <th scope = "row">{user.AEG_PERSON_NAMEEN}</th>
  <th scope = "row">{user.OLDPRDNO}</th>
  <th scope = "row">{user.PWNO}</th>
  <th scope = "row">{user.SALES_REF}</th>
  <th scope = "row">{user.JUM_PTYPE1}</th>
  <th scope = "row">{user.SALES_PERSON_NAMEEN}</th>
  <th scope = "row">{user.KEYWORD_ENDUSER}</th>
  <th scope = "row">{user.REPLIED_DATE.slice(0,10)}</th>
  <th scope = "row">{user.D}</th>
  </tr>);

this.setState({
...this.state, ...{
userList
}
});   
        }
         catch(e){
        console.log(`😱 Axios request failed: ${e}`);
      }
  };
}

export default TablePage;

Let's say I am making another page to display different information into the table, how do I run that server.js function with a different query? 假设我要创建另一个页面以在表中显示不同的信息,如何使用不同的查询运行该server.js函数? Do I really need to make another server2.js as the codes would be redundant? 我真的需要制作另一个server2.js,因为这些代码是多余的吗?

My ideal way is to just run a different query into the same function when changing to a different page but I just don't know how to do it in a different way other than creating another server2.js. 我的理想方法是在更改到不同的页面时仅对相同的函数运行不同的查询,但是除了创建另一个server2.js之外,我不知道如何以不同的方式进行操作。

what excactly you like to query? 您到底想查询什么? can you give 2 examples? 你能举两个例子吗? normaly you can fetch parameters with a route like: 通常,您可以使用以下路径来获取参数:

app.use('/user/:id', function (req, res) { app.use('/ user /:id',function(req,res){

let id = req.params.id let sqlQuery ="Select USER where id=" + id let id = req.params.id let sqlQuery =“选择用户,其中id =” + id

} }

sry for bad writing and coding, was quick n dirty by smartphone. 不好的写作和编码,很快就被智能手机弄脏了。

but i think i didnt understand the question exactly ;) 但我认为我不完全理解这个问题;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Node.js中,如何以不同的频率更新页面的不同组件? - In Node.js, how to update different components of a page in different frequency? 如何在不同端口上运行Signle Node.js项目 - How to run a signle node.js project on different ports 如何在node.js 4.2.3中执行具有不同超时的一个功能 - How to execute one function with different timeouts in node.js 4.2.3 如何使用 React 运行 node.js 服务器? - How run node.js server with React? 在CLI和node.js脚本中运行时,执行PHP脚本会产生不同的结果 - Executing PHP script has different results when run in CLI and by node.js script (Node.js和React.js)成功登录后如何删除/显示不同的按钮? - (Node.js & React.js) How to remove/show different buttons after logging in successfully? 如何在node.js中为不同的环境定义不同的变量? - How to define different vars for different environment in node.js? 根据Route显示不同的内容-Node.js / React - Displaying different content based on Route - Node.js/React 可能吗? 如何从不同目录中的不同node.js文件访问node.js文件? - is it possible? how to access node.js file from different node.js file in different directory? node.js集群:让每个工作人员呈现不同的页面 - node.js cluster: have each worker render different page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM