【发布时间】:2021-12-10 23:41:05
【问题描述】:
我正在尝试向服务器发出后端请求,并且我继续得到一个 response.data 返回,它是一些 HTML 字符串,上面写着 TypeError: Cannot read property of undefined
我需要向它传递一个看起来像这样的data 对象:
const data = {
visitorId,
patientId: oldPatientId,
doctorId
}
我需要像这样传递一个 json 网络令牌:
const userJWT = jwt.sign(
{
_id: visitorId,
refreshCount: 0
},
this.localConfig.spyrt.jwtSecret
)
以及看起来像这样的标题:
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${userJWT}`
}
我在这样的异步方法中执行此操作:
async jwtTest(visitorId: number, oldPatientId: number, doctorId: number): Promise<void> {
const data = {
visitorId,
patientId: oldPatientId,
doctorId
}
const userJWT = jwt.sign(
{
_id: visitorId,
refreshCount: 0
},
this.localConfig.spyrt.jwtSecret
)
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${userJWT}`
}
if (this.localConfig.spyrt.active) {
const dto = await axios.post(visitURL, data, {headers}).then((response) => {
console.log(response.data);
}).catch((error) => {
console.log(error);
});
}
}
我担心我的 axios 代码设置不正确。我收到无法读取未定义的属性和 500 statusCode 错误。
我已尽我所能查阅了 axios 文档。有人发现我的设置有什么问题吗?
我试过这个实现:
if (this.localConfig.spyrt.active) {
await axios.post(visitURL, data, {headers}).then(function(response) {
console.log(JSON.stringify(response.data));
}).catch(function(error) {
console.log(error);
})
}
有了这个,我得到了完全相同的响应。
最接近我理解的 API 是以前工程师的代码,其设置如下所示:
try {
let response = await fetch(visitURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + acct.jwt
},
body: JSON.stringify(visit)
});
if (response.ok) {
let result = await response.json();
callback(result);
} else {
throw new Error('Model: createVisit failed!');
}
} catch (error) {
console.log(error);
}
【问题讨论】:
-
具体是什么未定义,在哪里?给minimal reproducible example。如果是
dto,那么请注意,.then(() => { console.log("something") })不仅意味着你现在有一个未定义的承诺,它后面的.then(() => {})无论如何都会这样做。 -
从描述看来,服务器端发生了错误,而不是客户端。
-
@David,这是否意味着我的实现没有问题?
-
@Daniel:也许吧?测试和调试可以证实这一点。但是,您所做的任何此类测试和调试都应该非常明确地说明观察到的确切错误以及观察到的位置。这个错误信息是从服务器返回的吗?
-
同样,
.then在它之前记录,然后什么也不返回,也 导致整个承诺链解决未定义。但如果该消息在 response body 中,那么您处理响应的方式就不是那么重要了 - 500 表示服务器端错误,并且您没有向我们展示任何有关 API 实现的信息。你是否提出了错误的要求?也许吧,但即使是这样,也很难说哪个是正确的。
标签: javascript typescript axios