Use Typeorm + Express +mysql to build background projects

Document address:

  • 1. You can run ittypeorm init --name MyProject --database mysql --expressTo generate a more advanced Express project
typeorm init --name MyProject --database mysql --express
Copy the code
  • The directory structure
├ ─ ─ the README. Md ├ ─ ─ ormconfig. Json ├ ─ ─ package - lock. Json ├ ─ ─ package. The json ├ ─ ─ the SRC │ ├ ─ ─ controller │ │ └ ─ ─ Usercontroller. ├─ entity │ ├─ ├─ usercontroller. ├─ entity │ ├── ├.txtCopy the code

Document Description:

  • index.tsEntrance to the file
  • User.tsDefine table field and type files

Description: @entity write table name (do not write the default class name and lowercase)

  • Modify the ormconfig.json file

Document Description:

  • host IP address of the mysql host
  • port Port number of the mysql service
  • username User name of mysql
  • password The mysql password
  • database Database name
  • 3. Installation project dependency
Copy the code
  • 4. Modify packages.json file to add packaging configuration

  • 5. Modify the tsconfig.json file and change the output directory to dist

  • 6. Run projects
yarn start
Copy the code
  • 7. Build project
yarn build
Copy the code
  • 8. Test whether the packaged file can run
node dist/index.js
Copy the code

Note: An error is reportedSyntaxError: Cannot use import statement outside a module at Object.compileFunction (node:vm:352:18) at wrapSafe (node:internal/modules/cjs/loader:1031:15) at Module._compile (node:internal/modules/cjs/loader:1065:27) at Object.Module._extensions.. js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at /Users/jydata/Desktop/workSpace/ormexpress/node_modules/typeorm/util/ImportUtils.js:29:52

Error: ormconfig.json file configuration is loaded by default when the current project directory is running.

Solution: In modifying entities, Migrations and Subscribers, the path configured is dist/ XXXX (after modification).

You can also copy dist directory to other locations and run it. Note: after the test, I need to restore the configurations of entities, Migrations and Subscribers.

Supplementary note: When running on the server, you need to change the configuration directories of entities, migrations and Subscribers3 items in the ormconfig.json file to dist, SRC directory can not be uploaded to the server, and other files need to be uploaded

Note: The dist folder needs to be generated on the server. Do not upload the local DIST directly, otherwise the interface will report an error