[ITP404] Deploy to Netlify + Heroku

    科技2023-12-24  98

    TOC

    目标注意事项部署react portalJS tricks

    目标

    通过使用json-server建立一个服务器模拟api,并将其部署到Netlify+Heroku,使网页同时有前端和后端

    注意事项

    http protocol operates using strings: JSON.stringify() JSON.parse()

    response headers, request headers specify header - "Content-Type"

    put front end and api to the same domain to avoid athentication troubles proxy setting translate api domain to front end domain when depoying, needs to set up the api domain

    saveIssue function for both create and edit, using dynamic linking

    部署

    之前用surge更方便,不过surge不好配置json-server

    netlify

    support for proxing behaviorjust use to hold front end stuff create netlify.toml under src [[redirects]] from = "/api/*" to = "https://issues-app-json-server.herokuapp.com/api/:splat" status = 200 [[redirects]] from = "/*" to = "/index.html" status = 200

    proxy all api calls to heroku 2. Adjust api calls add /api prefix for every api call 3. package.json - leverage json-server on heroku json-server is only meant for development purpose, but you don’t want to host it. But for learning purpose… 4. create server.js under mock-api folder

    const jsonServer = require("json-server"); const server = jsonServer.create(); const router = jsonServer.router("mock-api/db.json"); const middlewares = jsonServer.defaults(); const port = process.env.PORT || 4000; server.use(middlewares); server.use("/api", router); server.listen(port); add json-server in dependencies of package.json and change “scripts”: locally run "json-server-dev": "nodemon mock-api/server.js" heroku run "json-server-prod": "node mock-api/server.js" use nodemon to avoid refreshing everytime we make change to server.jstell heroku to run json-server-prod - add a file Procfile under src web: npm run json-server-prod run npm install

    Log in to Netlify

    new site from git, select repo, select branch

    npm run build, build/ directory

    heroku.com, sign up

    new, create new app

    make app name unique (by setting the prefix)

    hook with github, choose repo, branch, enable automatic deploy (deploy for every change on github automatically)

    commit to deploy or click, see under activity

    More - view logs to debug if failed

    react portal

    useful for modal displays, as it is above all other components import {createPortal} from "react-dom" return createPortal( <div> Your HTML stuff </div>, document.getElementById("modal-container"))

    index.html <div id="modal-container"></div> as a child of the <body> tag

    Now the modal is not rendered under app.js’s return, but directly under body

    javascript from bootstrap does not work well with react, because of very different life cycle, so we only use css part of bootstrap Create functions in react to manage button clicks seperately, using states

    JS tricks

    compare objects, use id instead of comparing objects themselves

    Processed: 0.032, SQL: 8