weixin_33701251 2017-06-12 15:03 采纳率: 0%
浏览 54

Redux-Saga和Superagent

I need to make a request to my API endpoint to upload a file. I use axios across my project, but it looks like it's a problem to attach a file with it, while it should be straightforward with Superagent. However, my Saga code doesn't work with Superagent(no response object, API isn't triggered) What am I doing wrong?

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})
    }
}

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33737774 2017-06-28 14:33
    关注

    You need to use react sagas call-effect to call something that returns a promise. In your case, you're asking it to run the end-function, which is intended to be used with callbacks when you don't want to use promises. If you remove the end from your call line, you should see a request being made and should be getting a response:

    const response = yield call(req)
    

    Here you can find more about how to work with promises in superagent: http://visionmedia.github.io/superagent/#promise-and-generator-support

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法