我正在尝试使用Supertest向我的身份验证服务器发送POST请求,期望我打算将JWT存储在变量中。
以下是我的代码tokenGrabber.js
:
const fs = require('fs')
const supertest = require('supertest-with-proxy')
const agent = supertest.agent('<URL-for-auth-token-provider>')
const token = fs.readFileSync('./token.txt','utf-8');
const cookie = `token=${token};path=/;domain=domainName;`
let newToken = {}
async function setNewToken(){
const resp = await agent
.post('/token')
.proxy('http://<proxy-host:8080>')
.set('Cookie',cookie)
.timeout(5000)
.expect(200)
.then(function (error,response) {
if(error) {
newToken = undefined
throw error}
else {
console.log(response)
let refreshedCookie = JSON.parse(response.JSON)
fs.writeFile('./token.txt',refreshedCookie.token,function (err) {
if (err) throw err;
console.log('Saved!');
})
newToken = refreshedCookie.token
console.log(newToken)
}
})
}
setNewToken()
console.log(newToken)
我的目标是如果成功则启动newToken
,如果请求失败则启动undefined
。当我使用node tokenGrabber.js
运行此脚本时,它只打印一个空对象。 (我现在仅尝试打印它,因为我正在调试它,在确定逻辑可以正常工作之后,我将导出该变量)
完整输出:
{}
(node:3340) UnhandledPromiseRejectionWarning: Error: expected 200 "OK",got 500 "Internal Server Error"
at Test._assertStatus (/node_modules/supertest-with-proxy/lib/test.js:269:12)
at Test._assertFunction (/node_modules/supertest-with-proxy/lib/test.js:284:11)
at Test.assert (/node_modules/supertest-with-proxy/lib/test.js:174:18)
at localAssert (/node_modules/supertest-with-proxy/lib/test.js:132:12)
at /node_modules/supertest-with-proxy/lib/test.js:129:5
at Test.Request.callback (/node_modules/superagent/lib/node/index.js:728:3)
at parser (/node_modules/superagent/lib/node/index.js:916:18)
at IncomingMessage.res.on (/node_modules/superagent/lib/node/parsers/json.js:19:7)
at IncomingMessage.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
(node:3340) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3340) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
问题:我在做什么错?如果抛出错误,为什么不将变量更改为undefined?请评论在仍然使用超级测试的情况下是否有更清洁的方法来执行此操作。对于NodeJS和JS本身,我还是一个新手,对此表示赞赏。