我正在嘗試為我的一個朋友的學校專案制作一個類似運動/火種的應用程式。它在我的本地主機上很好地融合在一起,但對他來說,它是在線托管它的要求。不是真正的托管專業人士,但我對 Heroku 有點熟悉。我為我的應用程式使用了客戶端和服務器端,因此我構建了客戶端并將其放入服務器端檔案夾。此服務器端托管在 Heroku 頁面上,并顯示我的應用程式的首頁。但是每當我嘗試登錄時,它都不起作用,并且我在控制臺中收到此錯誤訊息。
?GET https://[app].herokuapp.com/dashboard 404 (Not Found)
Heroku 網頁上這樣說。
Cannot GET /dashboard
我知道還有很多其他人有同樣的問題。我嘗試了許多解決方案,但我認為我的路由可能有問題。我對 ReactJS 很陌生,所以我真的不知道路由是如何作業的。而且我更像是一名資料科學家,而不是一名軟體工程師,但我總是渴望學習這就是為什么我抓住機會學習這種新的“語言”。因此,當涉及到問題時,我可能是錯的。
這是我用來登錄的功能。這個功能在我的客戶端,所以我不確定當我構建到我的服務器端時它是否會傳輸。
const handleSubmit = async (e) => {
e.preventDefault()
try {
if( isSignUp && ( password !== confirmPassword)) {
setError('Passwords need to match!')
return
}
const response = await axios.post(`https://[app].herokuapp.com/${isSignUp ? 'signup' : 'login'}`, { email, password })
setCookie('AuthToken', response.data.token)
setCookie('UserId', response.data.userId)
const success = response.status === 201
if (success && isSignUp) navigate('/onboarding')
if (success && !isSignUp) navigate('/dashboard')
window.location.reload()
} catch (error) {
console.log(error)
}
}
我的index.js服務器的標頭
const PORT = process.env.PORT || 8000
const express = require('express')
const {MongoClient} = require('mongodb')
const {v1: uuidv4} = require('uuid')
const jwt = require('jsonwebtoken')
const cors = require('cors')
const bcrypt = require('bcrypt')
require('dotenv').config()
const uri = process.env.URI
const app = express()
app.use(cors())
app.use(express.json())
app.use(express.static(__dirname "/public"));
app.get('/', (req, res) => {
res.json('Hello to my app')
})
從我的index.js服務器注冊
app.post('/signup', async (req, res) => {
const client = new MongoClient(uri)
const {email, password} = req.body
const generateUserId = uuidv4()
const hashedPassword = await bcrypt.hash(password, 10)
try {
await client.connect()
const database = client.db('app-data')
const users = database.collection('users')
const existingUser = await users.findOne({email})
if (existingUser) {
return res.status((409).send('User already exists. Please login'))
}
const sanitizedEmail = email.toLowerCase()
const data = {
user_id: generateUserId,
email: sanitizedEmail,
hashed_password: hashedPassword
}
const insertedUser = await users.insertOne(data)
const token = jwt.sign(insertedUser, sanitizedEmail, {
expiresIn: 60 * 24,
})
res.status(201).json({token, userId: generateUserId})
} catch (err) {
console.log(err)
} finally {
await client.close()
}
})
從我的index.js服務器登錄
app.post('/login', async (req, res) => {
const client = new MongoClient(uri)
const {email, password} = req.body
try {
await client.connect()
const database = client.db('app-data')
const users = database.collection('users')
const user = await users.findOne({email})
const correctPassword = await bcrypt.compare(password, user.hashed_password)
if (user && correctPassword) {
const token = jwt.sign(user, email, {
expiresIn: 60 * 24
})
res.status(201).json({token, userId: user.user_id})
}
res.status(400).send('Invalid Credentials')
} catch (err) {
console.log(err)
} finally {
await client.close()
}
})
歡迎任何幫助。我希望我包含了足夠多的代碼示例,如果您需要更多,請回復;)
編輯
我的package.json檔案來自服務器目錄。
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"start:backend": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
客戶端目錄中的我的package.json檔案。
{
"name": "funfit",
"homepage": "https://[app].herokuapp.com/",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.2",
"@testing-library/react": "^12.1.4",
"@testing-library/user-event": "^13.5.0",
"axios": "^0.26.1",
"react": "^17.0.2",
"react-cookie": "^4.1.1",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.2",
"react-scripts": "5.0.0",
"react-tinder-card": "^1.4.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"start:frontend": "./node_modules/.bin/react-scripts start",
"build": "./node_modules/.bin/react-scripts build",
"test": "./node_modules/.bin/react-scripts test",
"eject": "./node_modules/.bin/react-scripts eject"
},
uj5u.com熱心網友回復:
這是我服務器的配置
/* import */
const path = require("path");
app.use(express.static(__dirname "/../client/build"));
app.get("*", (req, res) => {
// send index.html
let indexPath = path.join(__dirname, "/../client/build/index.html")
res.sendFile(indexPath);
});
看看這是否有效。我認為您的代碼的問題是僅發送主路由,因為僅給出“/”,但不確定。
確保您的 dirname 指向我現在看到的構建目錄,它僅指向公共
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475284.html
上一篇:為什么Django模型在執行緒池中回傳一個空的查詢集?
下一篇:我如何制作標題螢屏?
