简体   繁体   English

Redux-Saga和Superagent

[英]Redux-Saga and Superagent

I need to make a request to my API endpoint to upload a file. 我需要向我的API端点发出请求以上传文件。 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. 我在整个项目中都使用了axios,但是将文件附加到其中似乎是个问题,而对于Superagent来说应该很简单。 However, my Saga code doesn't work with Superagent(no response object, API isn't triggered) What am I doing wrong? 但是,我的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}) } } 

You need to use react sagas call -effect to call something that returns a promise . 您需要使用react sagas call effect来调用返回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. 在您的情况下,您要让它运行结束函数,该函数打算在不想使用promise时与回调一起使用。 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 在这里,您可以找到有关如何在超级代理中使用诺言的更多信息: http : //visionmedia.github.io/superagent/#promise-and-generator-support

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM