我正在尝试对用户进行身份验证。用户将用户名和密码发送到 express(使用 /login 端点),如果条目存在于数据库中,服务器将返回用户名。与用户名一起,在标头中返回一个 cookie,其中包含 json 网络令牌。重点是将 jwt 设置为客户端浏览器中的 cookie。系统成功验证用户并返回文本,但未设置 cookie。许多类似的问题都有为 axios 设置 withCredentials: true
的认可答案,但它似乎对我不起作用。 React 运行在 3001 端口,节点运行在 3000 端口。最初,我尝试使用 fetch:
fetch("http://localhost:3000/login", {
body: JSON.stringify({
Username: inputUsername,
Password: inputPassword,
}),
credentials: "same-origin",
method: "post",
url: "http://localhost:3000",
headers: new Headers({
"content-type": "application/json",
"access-control-allow-credentials": "true",
}),
})
.then((data) => data.json())
.then((data) => setName("Hello, " + data.text));
但无济于事。然后,我切换到 axios,希望有更多的 cookie 支持。
axios
.post("http://localhost:3000/login", {
method: "post",
Username: inputUsername,
Password: inputPassword,
withCredentials: true,
exposedHeaders: ["set-cookie"],
})
.then((response) => setName("Hello, " + response.data.text));
};
同样,它发送文本,但不设置 cookie。使用 Postman,我可以看到 cookie(拦截器打开): 但浏览器中没有任何内容: 以下是整个节点/快递代码:
const express = require("express");
const app = express();
const jwt = require("jsonwebtoken");
const cors = require("cors");
const { Pool } = require("pg");
var bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
app.use(cookieParser("MY SECRET"));
const pool = new Pool({
user: "",
host: "",
database: "",
password: "",
port: "",
});
app.use(bodyParser.json());
pool.connect();
app.use(
cors({
origin: "*",
credentials: true,
})
);
app.post("/login", async (req, res1) => {
res1.header("Content-Type", "application/json;charset=UTF-8");
res1.header("Access-Control-Allow-Credentials", true);
console.log();
await pool.query(
'SELECT "userSession" FROM task2database WHERE "Username"=$1 AND "Password"=$2',
[req.body.Username, req.body.Password],
(err, res) => {
if (res.rows.length > 0) {
let options = {
maxAge: 1000 * 60 * 15, // would expire after 15 minutes
httpOnly: true, // The cookie only accessible by the web server
signed: true, // Indicates if the cookie should be signed
};
res1.cookie(
"token",
jwt.sign({ user: req.body.Username }, "my_big_secret"),
options
);
res1.set({ "Access-Control-Allow-Credentials": true });
res1.json({ text: req.body.Username }).end();
}
console.log(res.rows);
}
);
console.log("Response sent");
});
app.listen(3000, () => {
console.log("Server is up!");
});
以下是整个 React 代码:
import React from "react";
import axios from "axios";
function App() {
const [name, setName] = React.useState("Waiting for login...");
const [inputUsername, setUsername] = React.useState("");
const [inputPassword, setPassword] = React.useState("");
const username = (e) => {
setUsername(e.target.value);
console.log(inputUsername);
};
const password = (e) => {
setPassword(e.target.value);
console.log(inputPassword);
};
const getName = (e) => {
console.log(inputUsername, inputPassword);
e.preventDefault();
axios
.post("http://localhost:3000/login", {
method: "post",
Username: inputUsername,
Password: inputPassword,
withCredentials: true,
exposedHeaders: ["set-cookie"],
})
.then((response) => setName("Hello, " + response.data.text));
};
return (
<div className="App">
{name}
<form onSubmit={getName}>
<input
onChange={username}
type="text"
name="username"
placeholder="User"
/>
<input
onChange={password}
type="text"
name="password"
placeholder="Pass"
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;