如何从reactJS前端访问Express后端



我在heroku上部署了我的react+express应用程序,但我似乎无法访问server.js中提供的登录api。

这是它在本地工作的前端,甚至在几次提交前也工作过,但它突然停止了。。。

<a href="/login">
<Button className="app-button" variant="success" size="lg" style={{marginTop:10, color: 'black'}}>
Log In
</Button>{' '}
</a>          

package.json:

{
"name": "spotifyproj",
"version": "0.1.0",
"private": true,
"homepage": " https://whispering-caverns-57172.herokuapp.com/",
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"bootstrap": "^4.5.2",
"compression": "^1.7.4",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"morgan": "^1.10.0",
"path": "^0.12.7",
"querystring": "^0.2.0",
"react": "^16.13.1",
"react-bootstrap": "^1.3.0",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3",
"react-spotify-player": "^1.0.4",
"spotify-web-api-js": "^1.5.0"
},
"scripts": {
"start": "node server.js",
"dev": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"heroku-postbuild": "npm install && npm run build"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

使用fetch/axios尝试并命中它也不起作用

React在客户端有路由,所以a标签什么都不做。

您需要一个类似fetch或axios的库来启动指向运行express服务器的url的post/login

import axios from 'axios';
const login = async () => {
const response = await axios.post('http://localhost/login');
// do something with response
}
return {
<Button onClick={() => login()}>
Log In
</Button>
}

最新更新