英文:
Why cant my server and client communicate?
问题
你的React应用运行在端口3001,服务器运行在端口3002。你的fetch代码似乎没有问题。错误信息显示"Uncaught (in promise) TypeError: Failed to fetch",这表明无法成功发起请求。
首先,确保你的Express服务器正常运行,并且没有其他错误。你可以检查服务器控制台输出以确认。
其次,确保你的React应用能够访问服务器。检查一下防火墙或跨域设置是否可能阻止了请求。
最后,你还可以使用浏览器的开发者工具来查看网络请求,以获取更多详细信息,可能有有关请求失败的信息。
希望这些提示有助于解决你的问题。如果需要进一步帮助,请提供更多信息。
英文:
i'm running react and a express server to handle the back-end but whenever I try and make an api call to my server.js it never goes through Im running the react client on port 3001 and the server on 3002
my fetch code looks like this:
// CreateAccount.js
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function CreateAccount() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [email, setEmail] = useState('');
const navigate = useNavigate();
const handleSubmit = async (event) => {
event.preventDefault();
const response = await fetch('http://localhost:3002/api/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, email }),
});
if (response.ok) {
navigate('/my-account.js'); // redirect to My Account page
}
}
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Username" value={username} onChange={e => setUsername(e.target.value)} required />
<input type="password" placeholder="Password" value={password} onChange={e => setPassword(e.target.value)} required />
<input type="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} required />
<button type="submit">Create Account</button>
</form>
);
}
export default CreateAccount;
and my server code looks like this:
const cors = require('cors');
const express = require('express');
const app = express();
const port = 3002;
const bcrypt = require('bcrypt');
const session = require('express-session');
// Use cors middleware
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}));
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
const { Pool } = require('pg');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'altuniai',
password: process.env.DATABASE_PASSWORD,
port: 5432,
});
...
app.post('/api/register', async (req, res) => {
try {
console.log('Received a POST request to /api/register with data:', req.body);
// hash the password
const hashedPassword = await bcrypt.hash(req.body.password, 10);
// store the new user in the database
const userId = await createUser(req.body.username, req.body.email, hashedPassword);
console.log(`User created with id: ${userId}`); // log the id of the created user
// log the user in
req.session.userId = userId;
// send a success response
res.status(201).send({ userId: userId });
} catch {
console.error('Error while registering user: ', error); // log any errors that occur
res.status(500).send();
}
});
...
and here is the full fetch error I'm getting:
Uncaught (in promise) TypeError: Failed to fetch
at handleSubmit (bundle.js:473:28)
at HTMLUnknownElement.callCallback (bundle.js:15215:18)
at Object.invokeGuardedCallbackDev (bundle.js:15259:20)
at invokeGuardedCallback (bundle.js:15316:35)
at invokeGuardedCallbackAndCatchFirstError (bundle.js:15330:29)
at executeDispatch (bundle.js:19474:7)
at processDispatchQueueItemsInOrder (bundle.js:19500:11)
at processDispatchQueue (bundle.js:19511:9)
at dispatchEventsForPlugins (bundle.js:19520:7)
at bundle.js:19680:16
Ive tried to put more stuff in the log but it wont even call to it which is why I think its a problem with the server communicating I'm just not sure what I have done wrong
答案1
得分: 1
我刚刚发现这是我的数据库错误,因为我忘记了那张表不叫做"passwords",对不起,我没有在正确的地方查找。
英文:
ok actually I just figured out it was an error from my database because I forgot that table isn't called passwords sorry I wasn't looking in the right place
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论