求助大神这是什么歌2,superagent 怎么使用 yield

SuperAgent使用简介
SuperAgent
SuperAgent是轻量级更为优化的ajax API,对比大量糟糕的现存的API,SuperAgent是灵活的、易读的、并且非常易学,同时SuperAgent可用于Node.js!
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.end(function(err, res){
if (err || !res.ok) {
alert('Oh no! error');
alert('yay got ' + JSON.stringify(res.body));
http://visionmedia.github.io/superagent/#buffering-responses
以下测试文档是使用Mocha的&doc& reporter生成的,并且直接反映测试套件,这提供一种文档的额外资源。
初始化一个请求可以通过调用request模块中适当的方法,然后使用.end()来发送请求,例如一个简单的GET请求:
.get('/search')
.end(function(err, res){
一个方法字符串也是允许的:
request('GET', '/search').end(callback);
支持ES6,可以使用.then()来代替.end()
request('GET', '/search').then(success, failure);
Node客户端也许提供绝对urls:
.get('/search')
.end(function(err, res){
DELETE, HEAD, POST, PUT以及其他HTTP请求都可使用,只需要简单的改变方法名称:
.head('/favicon.ico')
.end(function(err, res){
DELETE是特殊的保留字段,方法命名为.del():
.del('/user/1')
.end(function(err, res){
HTTP方法默认为GET,如果你想如此,以下示例是有效的:
request('/search', function(err, res){
设置头字段
设置头字段是简单的,使用字段名称和值来调用.set():
.get('/search')
.set('API-Key', 'foobar')
.set('Accept', 'application/json')
.end(callback);
你也可以在一个简单请求中通过传递一个对象来设置一些字段:
.get('/search')
.set({'API-Key': 'foobar', Accept: 'application/json'})
.end(callback);
.query()方法接受对象,当使用GET方法时将生成查询串,以下示例将生成路径/search?query=Manny&range=1..5&order=desc。
.get('/search')
.query({ query: 'Manny' })
.query({ range: '1..5' })
.query({ order: 'desc' })
.end(function(err, res){
或使用一个简单对象:
.get('/search')
.query({ query: 'Manny', range: '1..5', order: 'desc' })
.end(function(err, res){
.query()方法也接受字符串:
.get('/querystring')
.query('search=Manny&range=1..5')
.end(function(err, res){
.get('/querystring')
.query('search=Manny')
.query('range=1..5')
.end(function(err, res){
你也可以使用.query()方法来进行HEAD请求,以下示例将生成路径/users?email=
.head('/users')
.query({ email: '' })
.end(function(err, res){
POST/PUT请求
一个典型的JSON POST请求有点像以下示例,我们适当的设置Content-Type头字段,并且&写&一些数据,在此时只是一个JSON字符串
.post('/user')
.set('Content-Type', 'application/json')
.send('{&name&:&tj&,&pet&:&tobi&}')
.end(callback)
JSON无疑是使用最多的,它也是默认的!以下示例与之前的相同
.post('/user')
.send({ name: 'tj', pet: 'tobi' })
.end(callback)
或使用多个.send()请求:
request.post('/user')
.send({ name: 'tj' })
.send({ pet: 'tobi' })
.end(callback)
默认发送字符串将设置Content-Type为application/x-www-form-urlencoded,多个请求将使用&连接,这里结果是name=tj&pet=tobi:
request.post('/user')
.send('name=tj')
.send('pet=tobi')
.end(callback);
SuperAgent格式是可扩展的,但支持默认&json&和&form&,发送类似application/x-www-form-urlencoded的数据只需要调用&form&的.type(),这里默认是&json&,这种请求将会POST&name=tj&pet=tobi&
request.post('/user')
.type('form')
.send({ name: 'tj' })
.send({ pet: 'tobi' })
.end(callback)
Note:&form&别名为&form-data&和&urlencoded&并后向相容
设置Content-Type
之前的结论是使用.set()方法
request.post('/user')
.set('Content-Type', 'application/json')
.type()方法也可用于速记,接受规范化使用type/subtype完成的MIME类型名称,或简单的扩展名称例如&xml&,&json&,&png&等等:
request.post('/user')
.type('application/json')
request.post('/user')
.type('json')
request.post('/user')
.type('png')
序列化请求结构
SuperAgent会自动序列化JSON和格式,如果你想要再一个传统格式下发送一个有效载荷,你可以使用.serialize()方法替换内置序列化
通过速记方法.accept()设置接收头可以达成与.type()方法类似的效果,参考request.types允许你指定类似type/subtype的完全规范化MIME名称,或延期后缀格式类似&xml&、&json&、&png&:
request.get('/user')
.accept('application/json')
request.get('/user')
.accept('json')
request.post('/user')
.accept('png')
查询字符串
res.query(obj)方法可被用于建立一个查询字符串,例如在一个POST中填充?format=json&dest=/login
.post('/')
.query({ format: 'json' })
.query({ dest: '/login' })
.send({ post: 'data', here: 'wahoo' })
.end(callback);
解析返回结构
SuperAgent将解析已知的返回结构数据给你,当前支持application/x-www-form-urlencoded,application/json和multipart/form-data.
你可以使用.buffer(true).parse(fn)方法设置自定义解析(提升优先级高于建立解析),如果返回缓冲不可用(.buffer(false)),response事件将发出而不会等待结构解析器结束,因此response.body将不可用
JSON/Urlencoded
res.body属性是解析对象,例如如果一个请求返回JSON字符串&{&user&:{&name&:&tobi&}}&,res.body.user.name将变为&tobi&,同样&user[name]=tobi&的x-www-form-urlencoded值将产生同样的结果
Node客户端通过Formidable模块支持multipart/form-data,当解析multipart返回时,对象res.files对你也是可用的,假设例如一个请求响应如下multipart结构:
Content-Disposition: name=&image&; filename=&tobi.png&
Content-Type: image/png
... data here ...
Content-Disposition: form- name=&name&
Content-Type: text/plain
res.body.name将为&Tobi&,res.files.image作为一个File对象包含磁盘地址、文件名、和其他属性
很多有用的标志和属性设置在Response对象,范围包括返回文本、解析返回结构、头字段、状态标志等
res.text属性包含未解析返回结构字符串,这个属性会一直由客户端API提供,并且仅当mime类型匹配&text/&、&/json&或&x-www-form-urlencoded&默认为节点时,这是为了保存记忆,大型结构体的缓存文本,例如multipart文件或图片的效率是非常低的。
强制缓存可查看&缓存返回&部分
类似SuperAgent可以自动序列化请求数据,SuperAgent也可以解析它,当一个解析器定义Content-Type,他的解析方式默认包含&application/json&和&application/x-www-form-urlencoded&。解析对象通过res.body可用
返回头字段
res.header包含一个细节头字段的对象,小写字段名如节点一致,例如res.header['content-length']
返回Content-Type
Content-Type返回头是特殊情况,提供res.type,这是字符集的void(如果有的话),例如Content-Type值为&text/ charset=utf8&将提供res.type值为&text/html&,res.charset属性将包含&utf8&。
返回状态标志帮助决定请求是否成功、包含其他有用的信息,使得SuperAgent更理想的与RESTful web服务互动,这些标志当前定义如下:
var type = status / 100 | 0;
// status / class
res.status =
res.statusType =
res.ok = 2 ==
res.clientError = 4 ==
res.serverError = 5 ==
res.error = 4 == type || 5 ==
res.accepted = 202 ==
res.noContent = 204 == status || 1223 ==
res.badRequest = 400 ==
res.unauthorized = 401 ==
res.notAcceptable = 406 ==
res.notFound = 404 ==
res.forbidden = 403 ==
中止请求简单调用req.abort()方法
通过调用req.timeout(ms)可应用超时,调用之后错误将会触发,为区分其他错误,err.timeout属性设置为ms值。NOTE这是一个超时应用于请求和所有重定向,而不是对应每次请求
在所有Node和通过.auth()方法可用auth:
.get('http://local')
.auth('tobi', 'learnboost')
.end(callback);
在Node客户端基础auth可在URL中&user:pass&字段:
request.get('http://tobi:learnboost@local').end(callback);
默认只有Basicauth可用,在浏览器你可以添加{type:'auto'}来确保所有方法在浏览器(Digest、NTLM等)中建立
request.auth('digest', 'secret', {type:'auto'})
Following重定向
默认超过5个重定向将被followed,但是你可以使用res.redirects(n)方法来指定:
.get('/some.png')
.redirects(2)
.end(callback);
Piping数据
Node客户端允许你在请求中pipe传入传出数据,例如piping文件的内容作为请求:
var request = require('superagent')
, fs = require('fs');
var stream = fs.createReadStream('path/to/my.json');
var req = request.post('/somewhere');
req.type('json');
stream.pipe(req);
或piping返回到一个文件:
var request = require('superagent') ,
fs = require('fs');
var stream = fs.createWriteStream('path/to/my.json');
var req = request.get('/some.json');
req.pipe(stream);
Multipart 请求
SuperAgent也适用于建立multipart请求,为此提供了.attach()和.field()方法
如上所述,提供了一种更高级别的API,格式为.attach(name, [path], [filename])和.field(name, value)。附属几个文件很简单,你可以提供一个定制文件名作为附属,除非附属文件的基础名已经被使用了
.post('/upload')
.attach('avatar', 'path/to/tobi.png', 'user.png')
.attach('image', 'path/to/loki.png')
.attach('file', 'path/to/jane.png')
.end(callback);
类似HTML中的格式字段,你可以使用.field(name, value)设置字段值,假设你想上传一些图片以及你的名字和email,你的请求可以像下面这样:
.post('/upload')
.field('user[name]', 'Tobi')
.field('user[email]', '')
.attach('image', 'path/to/tobi.png')
.end(callback);
node客户端支持压缩返回,最好你不需要做任务事,它本身在工作中
为了强制返回结构缓冲为res.text,你可以调用req.buffer(),你可以调用req.buffer(false)来撤销默认缓存文本返回,例如&text/plain&,&text/html&等。
当res.buffered标志缓存已提供,你可以使用这个来处理在相同回调中的缓存或未缓存返回
.withCredentials方法确保可以发送cookies,但仅有当&Access-Control-Allow-Origin&不是通配符时(&*&),&Access-Control-Allow-Credent-ials&为&true&
.get('http://localhost:4001/')
.withCredentials()
.end(function(err, res){
assert(200 == res.status);
assert('tobi' == res.text);
你的回调函数始终传递两个参数:错误和返回,如果没有错误发送,第一个参数为空:
.post('/upload')
.attach('image', 'path/to/tobi.png')
.end(function(err, res){
An &error& event is also emitted, with you can listen for:
.post('/upload')
.attach('image', 'path/to/tobi.png')
.on('error', handle)
.end(function(err, res){
注意4xx或5xx的超级代理返回默认为错误,例如你获取一个500或403返回,使用err.status可使用这个状态信息,这种返回错误页包含了一个err.response字段,它有着&Response properties&中所有的上述状态。
网络失败,超时,和其他错误产生无返回将不包含err.status或err.response字段。
如果你处理404或其他HTTP错误返回,你可以查询err.status属性,当一个HTTP错误发生(4xx或5xx返回),res.error属性石一个Error对象,这允许你像这样执行检查:
if (err && err.status === 404) {
alert('oh no ' + res.body.message);
else if (err) {
// all other error types we handle generically
Promise and Generator support
SuperAgent的请求是一个&thenable&对象,它兼容Script语法和async/await句法。
类似co或koa可以在任何SuperAgent方法中产生:
var res = yield request
.get('http://local')
.auth('tobi', 'learnboost')
注意SuperAgent期望呈现全局Promise对象,在Internet Explorer或Node.js 0.10中你将需要一个polyfill来使用promises。
Facebook和接受JSON
如果你请求了Facebook的API,确保在你的请求中发送一个Accept: application/json头,如果你不想这样做,Facebook会返回Content-Type: text/javascript: charset=UTF-8,SuperAgent将不会解析并且res.body将不会定义,你可以使用req.accept('json')或req.header('Accept', 'application/json')。
浏览器和node版本
SuperAgent有两个实现:一个给浏览器(使用XHR),一个给Node.JS(使用核心http模板),默认Browserity和WebPack将采用浏览器版本
如果你想要使用WebPack来编译Node.JS代码,你必须在它的配置中指定node目标
在electron中使用浏览器版本
Electron开发者报告如果你使用SuperAgent的浏览器版本而不是Node版本时,你可以require('superagent/superagent'),你的请求将不会在Chrome开发者工具中表现出来,注意这个环境不被自动化测试包含斌并且不是正式支持的
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467142',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'小木虫 --- 500万硕博科研人员喜爱的学术科研平台
&&查看话题
求助大神们有谁知道quantum yield(量子收率)怎么测?
如题,本人做光催化,最近投稿,但是人让补一个量子收率(quantum yield)的试验,但是不知道怎么测,需要什么仪器,谢谢!急!:rol::rol:
恩,是的。
还是不太懂啊,如何测吸收和发光?
给我个邮箱,发给你详细的测量方法。
研究生必备与500万研究生在线互动!
扫描下载送金币
浏览器进程
打开微信扫一扫
随时随地聊科研ecmascript 6 - Promises es6 and superagent - Stack Overflow
to customize your list.
Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
J it only takes a minute:
I'm attempting to use es6 promises with superagent. I'm attempting to call a function that has a superagent request wrapped inside.
Request.post(buildReq).then(res =& {
if (res.ok) {//process res}
Here is the function wrapping superagent
static post(params) {
superagent
.post(params.url)
.send(params.payload)
.set('Accept', 'application/json')
.end((error, res) =& {
return this.Promise.resolve(res);
.bind(this);
I'm getting an error
enter code here Uncaught TypeError: Cannot read property 'then' of undefined
When I change the return of the function to
static post(params) {
return Promise.resolve(superagent
.post(params.url)
.auth(params.auth.username, params.auth.password)
.send(params.payload)
.set('Accept', 'application/json')
.end((error, res) =& {
return this.Promise.resolve(res);
It looks like the data is returned in my browser's dev tools, but I cannot get to it within the .then function. How can I get the response from the promise.
It doesn't matter what you're returning from the end method callback, as it asynchronously executed when you've get response and result of callback execution is nowhere used. Look
in the source code. end method returns this, so in your second example you're resolving superagent not response. To get response your post method must looks like:
static post(params) {
return new Promise((resolve, reject) =& {
superagent
.post(params.url)
.auth(params.auth.username, params.auth.password)
.send(params.payload)
.set('Accept', 'application/json')
.end((error, res) =& {
error ? reject(error) : resolve(res);
20.1k54965
Sometimes you'd like to avoid an indentation level caused by new Promise(...) then you can use directly Promise.reject and Promise.resolve.
static post(params) {
return superagent
.post(params.url)
.auth(params.auth.username, params.auth.password)
.send(params.payload)
.set('Accept', 'application/json')
.end((error, res) =& {
error ? Promise.reject(error) : Promise.resolve(res);
This is a more consise version, in case you need it for a lot of requests
import request from "superagent";
const withPromiseCallback = (resolve, reject) =& (error, response) =& {
if (error) {
reject({error});
resolve(response.body);
export const fetchSuggestions = (search) =& new Promise((resolve, reject) =&
get("/api/auth/get-companies/0/50").
type("form").
set("Accept", "application/json").
end(withPromiseCallback(resolve, reject))
export const fetchInitialInformation = () =& new Promise((resolve, reject) =&
get("/api/auth/check").
set("Accept", "application/json").
end(withPromiseCallback(resolve, reject))
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
rev .24822
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 求助大神 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信