今天的內容一樣以React為主,建立完前端應用程式之後,接著就是將前後端的應用程式連接。
/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
}
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);
/api
的請求,將回應的字串印出。comonentDidMount(){
fetch("/api")
.then(res=>res.json())
.then(data=>console.log(data))
.catch(err=>{console.log(err)});
}
今天的文章寫得有些倉促...果然臨時抱佛腳是很可怕的,因為遭遇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