[英]How to make a POST request with indicating userId?
有這樣的問題。 我希望使用用戶名創建帖子。 但是,當嘗試發出請求時,userId 始終等於 1。
↓↓↓
Postman
{
"id": 3,
"content": "content-5",
"userId": 1
}
楷模
const User = sequelize.define(
'users',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
username: { type: DataTypes.STRING, unique: true },
email: { type: DataTypes.STRING, unique: true },
password: { type: DataTypes.STRING },
role: { type: DataTypes.STRING, defaultValue: 'USER' },
},
{ timestamps: false }
);
const Post = sequelize.define(
'posts',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
content: { type: DataTypes.STRING, allowNull: false },
},
{ timestamps: false }
);
User.hasMany(Post, { foreignKey: 'userId' });
Post.belongsTo(User, { foreignKey: 'userId' });
后控制器
async create(req, res, next) {
try {
const { content } = req.body;
const { id: userId } = req.user;
const post = await Post.create({ content, userId })
return res.json(post)
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
您的問題似乎是您不知道如何處理 JWT 來檢索 session 數據
所以這是一個使用 jwt-simple 和 typescript的基本示例
編輯我已經從代碼中刪除了 TS
所以應該打電話來獲取令牌,例如
curl --request POST \
--url http://localhost:3000/auth \
--header 'Content-Type: application/json' \
--data '{
"usr": "user1",
"pwd": "123"
}'
這將達到一個端點,看起來像:
app.post("/auth", async (req, res) => {
const usr = req.body.usr;
const pwd = req.body.pwd;
//this would be a lookup on your database table not a basic if like i have here
if (usr === "user1" && pwd === "123") {
res.send(
encodeSession(secret, {
id: 7,
dateCreated: Date.now(),
username: usr,
})
);
} else res.send("Invalid login").sendStatus(403);
});
結果看起來像
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpZCI6NywiZGF0ZUNyZWF0ZWQiOjE2NTE2NTg3Njk3NTMsInVzZXJuYW1lIjoidXNlcjEiLCJpc3N1ZWQiOjE2NTE2NTg3Njk3NTMsImV4cGlyZXMiOjE2NTE2NTk2Njk3NTN9.JHY4Es9u-aDp1ZzbX-m5iOzbCqWisjqZQTST2nA2_6XUe5NSUbBSGpaXBd_IAlfsLjahJXAbNrxV6N-02E-h6g",
"issued": 1651658769753,
"expires": 1651659669753
}
然后在一個安全的端點你會打電話
function getUserDetails(req){
const [prefix, token] = req.headers.authorization?.split(" ");
if (prefix === "myToken" && token)
return decodeSession(secret, token));
else
throw new Error("Invalid token");
}
這將返回
{
"type": "valid",
"session": {
"id": 7,
"dateCreated": 1651658769753,
"username": "user1",
"issued": 1651658769753,
"expires": 1651659669753
}
}
對安全端點的調用看起來像
curl --request GET \
--url http://localhost:3000/checkauth \
--header 'Authorization: myToken eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpZCI6NywiZGF0ZUNyZWF0ZWQiOjE2NTE2NTg3Njk3NTMsInVzZXJuYW1lIjoidXNlcjEiLCJpc3N1ZWQiOjE2NTE2NTg3Njk3NTMsImV4cGlyZXMiOjE2NTE2NTk2Njk3NTN9.JHY4Es9u-aDp1ZzbX-m5iOzbCqWisjqZQTST2nA2_6XUe5NSUbBSGpaXBd_IAlfsLjahJXAbNrxV6N-02E-h6g' \
--header 'Content-Type: application/json'
為了完整起見,這里是 JWT-Simple 實現
import { encode, decode} from "jwt-simple";
export function encodeSession(
secretKey,
dataToEncode
){
// Always use HS512 to sign the token
const algorithm= "HS512";
// Determine when the token should expire
const issued = Date.now();
const fifteenMinutesInMs = 15 * 60 * 1000;
const expires = issued + fifteenMinutesInMs;
const session = {
...dataToEncode,
issued: issued,
expires: expires,
};
return {
token: encode(session, secretKey, algorithm),
issued: issued,
expires: expires,
};
}
export function decodeSession(
secretKey,
tokenString
){
// Always use HS512 to decode the token
const algorithm= "HS512";
let result={};
try {
result = decode(tokenString, secretKey, false, algorithm);
} catch (e) {
// These error strings can be found here:
// https://github.com/hokaccha/node-jwt-simple/blob/c58bfe5e5bb049015fcd55be5fc1b2d5c652dbcd/lib/jwt.js
if (
e.message === "No token supplied" ||
e.message === "Not enough or too many segments"
) {
return {
type: "invalid-token",
};
}
if (
e.message === "Signature verification failed" ||
e.message === "Algorithm not supported"
) {
return {
type: "integrity-error",
};
}
// Handle json parse errors, thrown when the payload is nonsense
if (e.message.indexOf("Unexpected token") === 0) {
return {
type: "invalid-token",
};
}
throw e;
}
return {
type: "valid",
session: result,
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.