使用Post API时出现500 Internal Server Error

时间:2019-02-23 19:08:11

标签: javascript reactjs api fetch saga

我也看到了此链接。但是它没有解决错误>>

https://forum.ghost.org/t/getting-500-internal-server-error-while-using-post-api/1422

实际上我使用了其他测试API,并且可以正常工作,但是我现在正在使用的该API出现此错误(500(内部服务器错误))!

我的请求>>

    const { apiRequest , dispatch , serviceKey } = this.props;

let params = {'action':'getList','subCatNumber':'1','parentCatName':'آرایشی، بهداشتی و سلامت'};

params = JSON.stringify(params);

dispatch(

    apiRequest( serviceKey , "subCategory", "POST", params ,
       {
           success     : this.loadSubCat1Success.bind(this) ,
           error       : this.loadCatError.bind(this)
       }
    )

);

我的配置>>

export default {
    apiUrl: 'http://myApi/',
};

我的动作>>

const actions = {
  SEND_REQUEST        : 'SEND_REQUEST',
  SEND_UPLOAD_REQUEST : 'SEND_UPLOAD_REQUEST',
  SERVICE_PENDING     : 'SERVICE_PENDING',
  SERVICE_ERROR       : 'SERVICE_ERROR',
  SERVICE_SUCCESS     : 'SERVICE_SUCCESS',
  RESPONSE_TYPE       : 'RESPONSE_TYPE',
  NOTIFICATION_ERROR  : 'NOTIFICATION_ERROR',
  apiRequest : ( serviceName = '' , url , method = "get", param = {} , callBacks = {} , baseURL = '' ) => ({
      type : actions.SEND_REQUEST ,
      serviceName ,
      url,
      method ,
      param ,
      callBacks,
      baseURL
  }),
  apiWithUpload : ( serviceName = '' , url, formData , callBacks = {} , auth = true , baseURL = '' ) => ({
      type : actions.SEND_UPLOAD_REQUEST ,
      serviceName ,
      url,
      formData ,
      callBacks,
      auth ,
      baseURL
  }),
  servicePending : ( mode , id ) => ({
      type      : actions.SERVICE_PENDING ,
      mode ,
      id
  }),
  serviceError : ( error , id ) => ({
      type      : actions.SERVICE_ERROR,
      error     : error ,
      id
  }),
  serviceSuccess : ( response , id ) => ({
      type      : actions.SERVICE_SUCCESS,
      response  : response ,
      id
  }),
  setStatus : ( mode , id ) => ({
      type      : actions.RESPONSE_TYPE ,
      mode ,
      id
  }),
  setErrorNotify : ( message , id ) => ({
      type      : actions.NOTIFICATION_ERROR ,
      message ,
      id
  })
};


export default actions;

我的减速器>>

import { Map } from 'immutable';
import actions from './actions';

const initState = new Map({
    error       : {} ,
    response    : {} ,
    pending     : {} , //0 or 1
    status      : {} //success or error
});

export default function apiReducer(state = initState, action) {

  let service = action.id;

  switch (action.type) {

      case actions.RESPONSE_TYPE: 

        return state.set('status', {
            ...state.get('status'),
            [service] : action.mode
        });

    case actions.NOTIFICATION_ERROR:

        return state.set('error', {
            ...state.get('error'),
            [service] : action.message
        });

    case actions.SERVICE_SUCCESS:

        return state.set('response', {
            ...state.get('response'),
            [service] : action.response
        });

    case actions.SERVICE_PENDING:


        return state.set('pending', {
            ...state.get('pending'),
            [service] : action.mode
        });

    default:

      return state;

  }
}

我的传奇>>

import { all, takeEvery, put, fork } from 'redux-saga/effects';
import {getToken} from '../../components/helpers/utility';
import actions from './actions';
import authActions from '../auth/actions';
import config from "../../config";
import axios from "axios/index";
import querystring from 'querystring';
import _ from "underscore";

let axiosOverride = axios.create({

});

const filterError = (error) => {

    let message = "";

    if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        if (error.response.data && error.response.data.error) {

            message = error.response.data.error;

        } else {

            message = "global.invalid_ajax_response";//error.response.statusText;

        }

    } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        message = "global.invalid_received_response";//error.request;
    } else {
        // Something happened in setting up the request that triggered an Error
        message = "global.invalid_ajax_request";//error.message;
    }

    return message;
};

export function* sendRequest() {

    yield takeEvery(actions.SEND_REQUEST, function*( action ) {

        let { url, method , param , auth , baseURL , serviceName , callBacks } = action;

        if( !baseURL ){
            baseURL = config.apiUrl;
        }

        url = baseURL + url;

        const accessToken = getToken().get('idToken');

        let options = {
            method  : method,
            url     : url
        };

        if( method.toLowerCase() === "get" ){

            options.params = param;

        }else{

            options.data = querystring.stringify( param );

        }

        options.headers = {};

        if( auth ){
            options.headers.Authorization = 'Bearer ' + accessToken;
        }
        options.headers.Accept = "application/json";

        options.withCredentials = false;

        if (method.toLowerCase() === "post"){

            // options.headers['Content-Type'] = 'application/raw';

        }

        yield put( actions.servicePending( 1 , serviceName ) );

        try {

            const response = yield axiosOverride( options );

            yield put( actions.servicePending( 0 , serviceName ) );

            yield put( actions.setStatus( "success" , serviceName ) );

            yield put( actions.serviceSuccess( response , serviceName ) );

            if( !_.isUndefined( callBacks ) && !_.isUndefined( callBacks.success ) && _.isFunction( callBacks.success ) ){

                callBacks.success.apply( null , [ response , param , serviceName ] );

            }

        } catch (e) {

            yield put( actions.servicePending( 0 , serviceName ) );

            yield put( actions.setStatus( "error" , serviceName ) );

            yield put( actions.serviceError( e , serviceName ) );

            if( !_.isUndefined( callBacks ) && !_.isUndefined( callBacks.error ) && _.isFunction( callBacks.error ) ){

                callBacks.error.apply( null , [ filterError( e ) , param , serviceName ] );

            }

        }


    });

}

export function* sendRequestWithUpload() {

    yield takeEvery(actions.SEND_UPLOAD_REQUEST, function*( action ) {

        let { url, formData , auth , baseURL , serviceName , callBacks } = action;

        if( !baseURL ){
            baseURL = config.apiUrl;
        }

        url = baseURL + url;

        const accessToken = getToken().get('idToken');

        let options = {};

        options.headers = {};

        if( auth ){
            options.headers.Authorization = 'Bearer ' + accessToken;
        }

        options.headers.Accept = "application/json";

        options.withCredentials = false;

        options.headers['Content-Type'] = 'multipart/form-data';

        yield put( actions.servicePending( 1 , serviceName ) );

        try {

            const response = yield axiosOverride.post( url , formData , options );

            yield put( actions.servicePending( 0 , serviceName ) );

            yield put( actions.setStatus( "success" , serviceName ) );

            yield put( actions.serviceSuccess( response , serviceName ) );

            if( !_.isUndefined( callBacks ) && !_.isUndefined( callBacks.success ) && _.isFunction( callBacks.success ) ){

                callBacks.success.apply( null , [ response , formData , serviceName ] );

            }

        } catch (e) {

            /*console.error(e);*/

            yield put( actions.servicePending( 0 , serviceName ) );

            yield put( actions.setStatus( "error" , serviceName ) );

            yield put( actions.serviceError( e , serviceName ) );

            if( !_.isUndefined( callBacks ) && !_.isUndefined( callBacks.error ) && _.isFunction( callBacks.error ) ){

                callBacks.error.apply( null , [ filterError( e ) , formData , serviceName ] );

            }

        }


    });

}

export function* requestError() {

    yield takeEvery(actions.SERVICE_ERROR, function*( action ) {

        let error = action.error;

        if( typeof error.response != "undefined"  ){

            const response = error.response;

            if( response.status === 401 ) {

                yield put( { type : authActions.LOGOUT } );

            }else{

                if (response.data && response.data.error) {

                    yield put( actions.setErrorNotify( response.data.error , action.id ) );

                } else {

                    yield put( actions.setErrorNotify( response.statusText , action.id ) );

                }

            }

        }else {

            yield put( actions.setErrorNotify( error.message , action.id ) );

        }

    });

}


export default function* rootSaga() {
  yield all([
    fork(sendRequest) ,
    fork(requestError) ,
    fork(sendRequestWithUpload)
  ]);
}

0 个答案:

没有答案