求助:将request调用Auth0 OAuth的代码迁移至Supertest时遇错
解决Supertest迁移时的POST请求错误
首先得明确:Supertest主要设计用来测试本地Express服务器,不过也可以用来发送外部API请求,但用法和直接用request/superagent略有区别。咱们来逐个解决你的问题:
第一个错误:TypeError: (0 , _superagent.default)(...).post is not a function
你之前的写法request('https://domain.auth0.com/oauth/token').post()是错误的——当你给request()传入完整URL时,返回的是一个绑定了该base URL的agent实例,它的.post()方法需要传入相对路径(比如/oauth/token),而不能留空。
如果要直接发送POST到完整外部URL,应该直接用request.post(完整URL)的形式,而不是先调用request(URL)再链式.post()。
第二个错误:Error: expected 200 "OK", got 404 "Not Found"
这个问题出在你拆分URL的方式上,Supertest的agent在处理base URL + 路径时,可能会对路径做拼接处理(比如自动补斜杠),导致最终请求的URL不符合Auth0的要求,所以返回404。
正确的迁移写法
结合你的需求,正确的Supertest代码应该是这样的:
import request from 'supertest'; describe('get a token', function () { it('should return an access token', async function() { await request.post('https://domain.auth0.com/oauth/token') .set('content-type', 'application/x-www-form-urlencoded') .send({ grant_type: "password", username: "someone@email.com", password: "myPassword", audience: "https://some-place.com", client_id: "long-string", client_secret: "even-longer-string" }) .expect(200); }); });
或者也可以用.type('form')来简化content-type的设置(Supertest会自动帮你设置为application/x-www-form-urlencoded):
import request from 'supertest'; describe('get a token', function () { it('should return an access token', async function() { await request.post('https://domain.auth0.com/oauth/token') .type('form') .send({ grant_type: "password", username: "someone@email.com", password: "myPassword", audience: "https://some-place.com", client_id: "long-string", client_secret: "even-longer-string" }) .expect(200); }); });
关键注意点:
- 不要用
.field()方法——这个方法是用来发送multipart/form-data类型的表单数据的,而你需要的是application/x-www-form-urlencoded,直接用.send()传对象即可。 - 如果要复用base URL(比如多个测试用同一个域名),可以先创建agent,再指定路径:
这种方式要确保路径拼接正确,比如const auth0Agent = request('https://domain.auth0.com'); // 在测试里使用 await auth0Agent.post('/oauth/token') .type('form') .send(...) .expect(200);/oauth/token前面的斜杠不能丢。
最后补充一句:如果你的测试主要是调用外部API,其实直接用superagent(Supertest就是基于它的)可能更直观,不过用Supertest配合Mocha做断言也完全没问题。
内容的提问来源于stack exchange,提问作者klequis
相关产品推荐
相关产品推荐

