我在mern stack中创建了一个社交媒体,并且在开发中一切都很好。但是在生产中,我的请求有问题。
为了更好地解释,首先我的问题是一个cookie问题,我需要一个cookie让用户登录,起初,请求是ok的(代码200),但我没有cookie,用户没有连接。现在,在对cookie进行了一些更改后,请求不正确(错误400),似乎前端不与后端通信。我不知道哪里会出错。
我的应用程序托管在heroku(背面和正面),我买了一个域名,谁是https://www.universegram.fr
我把我的开发代码放在下面,在我为生产所做的更改之后。
<标题>开发代码Server.js
const app = express();
const PORT = process.env.PORT || 5000
const corsOptions = {
origin: "http://localhost:3000",
credentials: true,
"allowedHeaders": ["sessionId", "Content-Type"],
"exposedHeaders": ["sessionId"],
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false
}
app.use(cors(corsOptions));
app.set("trust proxy", 1);
// Read bodys and cookies on our requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
// jwt middleware
app.get("*", checkUser);
app.get("/jwtid", requireAuth, (req, res) => {
res.status(200).send(res.locals.user._id)
});
// Routes
app.use("/api/user", userRoutes);
app.use("/api/post", PostRoutes);
// Server static assets if in production
if(process.env.NODE_ENV === "production"){
// Set static folder
app.use(express.static("client/build"))
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
})
}
// Server
app.listen(PORT, () => {
console.log(`Server is running on ${process.env.PORT
}`);
})
AuthController.js (SignIn方法)
module.exports.signIn = async (req, res) => {
const { email, password } = req.body;
try {
const user = await UserModel.login(email, password);
const token = createToken(user._id);
res.cookie("jwt", token, {
maxAge: maxAge,
sameSite: "lax",
// httpOnly: true,
secure: false,
})
res.status(200).json({ user: user._id })
}
catch (err) {
const errors = signInErrors(err);
res.status(400).json({ errors });
// console.log(err)
}
}
我的包。json(客户端)
{
"name": "client",
"version": "0.1.0",
"private": true,
"homepage": "/",
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.0.1",
"@testing-library/user-event": "^13.5.0",
"firebase": "^9.7.0",
"hamburger-react": "^2.5.0",
"particlesjs": "^2.2.3",
"react": "^18.0.0",
"react-burger-menu": "^3.0.6",
"react-dom": "^18.0.0",
"react-scripts": "5.0.1",
"sass": "^1.50.0",
"web-vitals": "^2.1.4"
},
"proxy": "http://localhost:5000",
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "craco 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"
]
},
"devDependencies": {
"dotenv": "^16.0.0",
"js-cookie": "^3.0.1",
"react-redux": "^7.2.8",
"react-router-dom": "^6.3.0",
"reactjs-popup": "^2.0.5",
"redux": "^4.1.2",
"redux-devtools-extension": "^2.13.9",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.4.1"
}
}
<标题>生产变化(改变原点)
const corsOptions = {
origin: "https://www.universegram.fr",
credentials: true,
"allowedHeaders": ["sessionId", "Content-Type"],
"exposedHeaders": ["sessionId"],
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false
}
(更改cookie设置)
module.exports.signIn = async (req, res) => {
const { email, password } = req.body;
try {
const user = await UserModel.login(email, password);
const token = createToken(user._id);
res.cookie("jwt", token, {
maxAge: maxAge,
sameSite: "none",
// httpOnly: true,
secure: true,
})
res.status(200).json({ user: user._id })
}
catch (err) {
const errors = signInErrors(err);
res.status(400).json({ errors });
// console.log(err)
}
}
我尝试了很多东西,但直到现在我还没有找到好的解决方案..如果你能帮助我,提前感谢。
标题>标题>谢谢你的回答,我看了看,从我的前端,从我的请求,没有什么,它直接在catch方法。这是我的SignIn组件:
const SignInForm = () => {
const { uid, setUid } = useContext(UidContext);
const navigate = useNavigate();
const dispatch = useDispatch();
// States to take the inputs values
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
// console.log(uid)
// Function to login the user or display the errors
const handleLogin = (e) => {
e.preventDefault();
const emailError = document.querySelector(".email.error");
const passwordError = document.querySelector(".password.error");
axios({
method: "post",
url: `/api/user/login`,
withCredentials: true,
data: {
email,
password
}
})
.then((res) => {
console.log(res)
if (res.data.errors) {
emailError.innerHTML = res.data.errors.email;
passwordError.innerHTML = res.data.errors.password;
}
else {
dispatch(getUser(res.data.user))
.then(() => dispatch(getUsers()))
.then(() => setUid(res.data.user))
.then(() => navigate("/home"))
}
// navigate("/home")
})
.catch((err) => {
console.log(err + "C'est chelou");
})
}
return (
<form action="" onSubmit={handleLogin} id="sign-up-form" >
<label htmlFor="email">Email</label>
<input type="text"
name="email"
id="email"
onChange={(e) => setEmail(e.target.value)}
value={email} />
<div className="email error"></div>
<br />
<label htmlFor="password">Mot de passe</label>
<input type="password"
name="password"
id="password"
onChange={(e) => setPassword(e.target.value)}
value={password} />
<div className="password error"></div>
<br />
<input type="submit" value="Se connecter" />
</form>
)
}