我需要在req.headers
中获取userId
,但我无法正确地输入它,我该如何做?
首先我尝试了以下方法:
interface ISpot{
thumbnail: File,
company: string,
price: number,
techs: string
}
interface IReqCustom<T> extends Request{
body: T,
}
export default {
async store (req: IReqCustom<ISpot>, res: Response): Promise<Response> {
const { filename } = req.file
const { company, techs, price } = req.body
const { userId } = req.headers
const user = await User.findById(userId)
if (!user) {
return res.status(400).json({ error: 'User doesn\'t exist' })
}
const spot = await Spot.create({
user: userId,
thumbnail: filename,
company,
techs: techs.split(',').map(tech => tech.trim()),
price
})
return res.json(spot)
}
}
第34行的用户键必须是一个字符串,但它从
userId
接收到的值可能是string | string [] | undefined
。我也尝试过这个:
interface UserHeader{
userId: string
}
interface IReqCustom<T, P> extends Request{
body: T,
headers: P
}
async store (req: IReqCustom<ISpot, UserHeader>, res: Response): Promise<Response>{}
用户分配错误已消失,但接口
IReqCustom
出现了另一个错误。Interface 'IReqCustom<T, P>' incorrectly extends interface 'Request<ParamsDictionary, any, any, ParsedQs>'.
Types of property 'headers' are incompatible.
Type 'P' is not assignable to type 'IncomingHttpHeaders'.
我该如何使这些属性识别其各自的类型?
express
吗? - guriskoimport { Request, Response } from 'express'
。 - Jose Carlos Filho