Day26 NodeJS中的前端框架 II

今天的内容一样以React为主,建立完前端应用程序之後,接着就是将前後端的应用程序连接。

  1. 首先在React应用程序专案中的package.json加上服务器应用程序的URL作为proxy,proxy的设定可以让应用程序在请求Path时,自动代理为proxy网址中的Path,例如:/api会请求http://localhost:2000/api
{
  "name": "reacttest",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "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"
    ]
  },
  "proxy": "http://localhost:2000"	//新增proxy
}
  1. 服务器程序码中新建一个Path为api的get方法,并回传JSON格式字串。
let express = require("express");
let app = express();
let port = process.env.PORT || 2000;

//加入get方法
app.get("/api", (req, res)=>{
    res.setHeader("contentType", "application/json");
    res.end(JSON.stringify({data:"Hello, chwk"}));
    console.log("send message");
});

app.listen(port);
  1. 建立好後端的方法之後,在前端应用程序中加入对/api的请求,将回应的字串印出。
comonentDidMount(){
    fetch("/api")
    .then(res=>res.json())
    .then(data=>console.log(data))
    .catch(err=>{console.log(err)});
  }
  1. 执行後可以在开发人员工具看到印出字串。

https://ithelp.ithome.com.tw/upload/images/20211012/20139980vJbYjXoIug.png

小结

今天的文章写得有些仓促...果然临时抱佛脚是很可怕的,因为遭遇fetch不到的问题,尝试了改proxy、fetch绝对路径等方法,最後是透过package.json的锁定档删除重装,才顺利的使proxy可以作用。

参考资料

https://snh90100.medium.com/快速整合-express-js-到-react-js-专案内-492e131800ec
https://www.freecodecamp.org/news/how-to-create-a-react-app-with-a-node-backend-the-complete-guide/
https://jasonwatmore.com/post/2020/01/27/react-fetch-http-get-request-examples
https://stackoverflow.com/questions/48291950/proxy-not-working-for-react-and-node


<<:  Day26 interrupt, exception

>>:  【第26天】探讨与改善-增加训练样本(一)

[Day 20]从零开始学习 JS 的连续-30 Days---todolist 待办事项

待办事项结构 to do list 需要输入框与输入按钮。 送出输入按钮後产生待办事项与完成按钮。 ...

Day30:HTML(28) form(7)

输入类型文件 该"input type="file"" 定义...

Day 11 : 操作基础篇 8 - 倍速提升你的操作速度,14 个 Obsidian 快捷键设定建议

前言 这是 Obsidian 使用教学 — 基础篇的第 8 篇文章。 在 上一篇文章 中,我介绍了一...

JavaScript Day01 - 说明

前言 这次主要是更新我之前的笔记,那时候刚学习 JavaScript,对於一些结果可能不是很懂,刚好...

Day 15 — To Do List (1) 了解 HTML Service

昨天我们做完前置作业了,今天我们来看一下这个 HTML Service 是怎麽用! 简单来说,就是可...