【问题标题】:Redux-Saga and SuperagentRedux-Saga 和 Superagent
【发布时间】:2017-11-14 02:55:12
【问题描述】:

我需要向我的 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})
    }
}

【问题讨论】:

    标签: javascript ajax redux redux-saga superagent


    【解决方案1】:

    您需要使用 react sagas call-effect 来调用返回承诺的东西。在您的情况下,您要求它运行 end-function,当您不想使用 Promise 时,该函数旨在与回调一起使用。如果您从呼叫线路中删除结尾,您应该会看到正在发出请求并且应该得到响应:

    const response = yield call(req)
    

    您可以在此处找到有关如何在 superagent 中使用 Promise 的更多信息: http://visionmedia.github.io/superagent/#promise-and-generator-support

    【讨论】: