我需要向我的API端点请求上传一个文件。我在我的项目中使用了axios,但是与它一起附加一个文件似乎是个问题,而使用Superagent应该是简单明了的。但是,我的Saga代码不适用于Superagent(没有响应对象,API没有触发),我做错了什么?
import { delay } from 'redux-saga';
import { select, call, put } from 'redux-saga/effects';
import request from 'superagent'
import * as action from '../../constants/actions/';
import config from '../../constants/config';
import { getFile, selectEntity, selectPreview } from '../../selectors';
export default function* putUserpic() {
const file = yield select(getFile)
const API = process.env.API_URL || config.API_URL;
const entity = yield select(selectEntity);
const requestURL = `${API}/${entity}/userpic`;
const token = localStorage.getItem(config.TOKEN);
var req = request.post(requestURL)
.attach(file.name, file)
.set('authorization', token);
try {
yield put({type: action.REQ_PENDING});
const response = yield call(req.end)
yield put({type: action.RES_RECEIVED})
yield put({type: action.MESSAGE, payload: response.data.message});
} catch (e) {
yield put({type: action.RES_RECEIVED})
yield put({type: action.AUTH_ERROR, payload: e.response.data.error});
yield delay(config.MSG_DELAY);
yield put({type: action.RESET_ERROR})
} finally {
yield delay(config.MSG_DELAY);
yield put({type: action.RESET_MESSAGE})
}
}
发布于 2017-06-28 14:33:26
您需要使用react call-effect来调用返回的承诺。在您的例子中,您要求它运行end函数,当您不想使用承诺时,它将用于回调。如果您从呼叫线路中删除了终端,您应该会看到一个请求正在发出,并且应该得到响应:
const response = yield call(req)在这里,您可以找到关于如何在超级代理中使用承诺的更多信息:http://visionmedia.github.io/superagent/#promise-and-generator-support
https://stackoverflow.com/questions/44502687
复制相似问题