简体   繁体   中英

How to query mysql from google cloud sql instance in React

I am trying to query and retrieve users' tables from my MySQL database that I already connected using MySQL workbench.

I've read in the documentation that I need to use the express API to do this. I installed the API and wrote the example code to my preference. but I keep getting an error saying: TypeError: express is not a function

I am new to React so I don't understand what's wrong exactly.

Please if you can guide me on what I am doing wrong.

Here is my code:

signup.js:

require('dotenv').config()

const express = require('express');
const app = express(); // i am getting the error from this line.
const bodyParser = require('body-parser');
const connection = require('../database');

app.route('/users/:id')
  .get(function(req, res, next) {
    connection.query(
      "SELECT * FROM `users` WHERE id = ? ", req.params.id,
      function(error, results, fields) {
        if (error) throw error;
        res.json(results);
      }
    );
  });

app.get('/status', (req, res) => res.send('Working!'));

// Port 8080 for Google App Engine
app.set('port', process.env.PORT || 3000);
app.listen(3000);

package.json:

{
  "name": "appname",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.10",
    "@testing-library/react": "^11.2.5",
    "@testing-library/user-event": "^12.8.3",
    "bootstrap": "^4.6.0",
    "express": "^4.17.1",
    "firebase": "^8.9.1",
    "mysql": "^2.18.1",
    "node-sass": "^5.0.0",
    "react": "^17.0.2",
    "react-bootstrap": "^1.5.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "react-slick": "^0.28.1",
    "react-tradingview-widget": "^1.3.2",
    "slick-carousel": "^1.8.1",
    "web-vitals": "^1.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

You could remove your node_modules/ folder and then reinstall the dependencies from package.json.

rm -rf node_modules/
npm install

This would erase all installed packages in the current folder and only install the dependencies from package.json.

did you confirm that express are in node_modules ? To make sure, execute another npm install after deleting your node_modules folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM