Axios to Node(Express)GET请求

时间:2017-07-19 16:10:02

标签: javascript node.js reactjs redux axios

所以使用axios,我试图向我的快递服务器发出请求,这是我的Axios请求:

/* @flow */

import type {
  Dispatch,
  GetState,
  ThunkAction,
  Reducer,
} from '../../types';

export const USERS_INVALID = 'USERS_INVALID';
export const USERS_REQUESTING = 'USERS_REQUESTING';
export const USERS_FAILURE = 'USERS_FAILURE';
export const USERS_SUCCESS = 'USERS_SUCCESS';

export const API_URL = '/api/articleList';

// Export this for unit testing more easily
export const fetchUsers = (axios: any, URL: string = API_URL): ThunkAction =>
  (dispatch: Dispatch) => {
    dispatch({ type: USERS_REQUESTING });

    return axios.get(URL)
      .then((res) => {
        dispatch({ type: USERS_SUCCESS, data: res.data });
      })
      .catch((err) => {
        dispatch({ type: USERS_FAILURE, err });
      });
  };

// Preventing dobule fetching data
/* istanbul ignore next */
const shouldFetchUsers = (state: Reducer): boolean => {
  // In development, we will allow action dispatching
  // or your reducer hot reloading won't updated on the view
  if (__DEV__) return true;

  const userListFetch = state.userListFetch;

  if (userListFetch.readyStatus === USERS_SUCCESS) return false; // Preventing double fetching data

  return true;
};

/* istanbul ignore next */
export const fetchUsersIfNeeded = (): ThunkAction =>
  (dispatch: Dispatch, getState: GetState, axios: any) => {
    /* istanbul ignore next */
    if (shouldFetchUsers(getState())) {
      /* istanbul ignore next */
      return dispatch(fetchUsers(axios));
    }

    /* istanbul ignore next */
    return null;
  };

这是我在快递服务器上的代码:

//GET ARTICLES
app.get('/api/articleList', (req, res) => { 
  console.log('hello');
});

它没有记录“hello”并且它没有显示任何错误,我只是觉得我错过了一些让Axios到达我服务器的东西......

我在另一个应用程序上有类似的工作,但似乎无法在这里实现它,我在网上搜索,找不到解决方案,感谢任何帮助或建议 - 谢谢你提前!

  

注意:当“API_URL”变量为时,Axios请求正常工作   设置为myjson url链接,所以我知道我的动作很好,我觉得   就像我错过了一些东西才能到达我的服务器

编辑:请查看我的整个server.js:

/* @flow */

import path from 'path';
import morgan from 'morgan';
import express from 'express';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import favicon from 'serve-favicon';
import React from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { matchRoutes } from 'react-router-config';
import { Provider } from 'react-redux';
import chalk from 'chalk';

import createHistory from 'history/createMemoryHistory';
import configureStore from './redux/store';
import Html from './utils/Html';
import App from './containers/App';
import routes from './routes';
import { port, host } from './config';

const app = express();

// Using helmet to secure Express with various HTTP headers
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());

// Use morgan for http request debug (only show error)
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));
app.use(favicon(path.join(process.cwd(), './build/public/favicon.ico')));
app.use(express.static(path.join(process.cwd(), './build/public')));

// Run express as webpack dev server
if (__DEV__) {
  const webpack = require('webpack');
  const webpackConfig = require('../tools/webpack/webpack.client.babel');

  const compiler = webpack(webpackConfig);

  app.use(require('webpack-dev-middleware')(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    noInfo: true,
    stats: 'minimal',
  }));

  app.use(require('webpack-hot-middleware')(compiler));
}

// Register server-side rendering middleware
app.get('*', (req, res) => {
  if (__DEV__) webpackIsomorphicTools.refresh();

  const history = createHistory();
  const store = configureStore(history);
  const renderHtml = (store, htmlContent) => {  // eslint-disable-line no-shadow
    const html = renderToStaticMarkup(<Html store={store} htmlContent={htmlContent} />);

    return `<!doctype html>${html}`;
  };

  // If __DISABLE_SSR__ = true, disable server side rendering
  if (__DISABLE_SSR__) {
    res.send(renderHtml(store));
    return;
  }

  // Load data on server-side
  const loadBranchData = () => {
    const branch = matchRoutes(routes, req.url);

    const promises = branch.map(({ route, match }) => {
      // Dispatch the action(s) through the loadData method of "./routes.js"
      if (route.loadData) return route.loadData(store.dispatch, match.params);

      return Promise.resolve(null);
    });

    return Promise.all(promises);
  };

  // Send response after all the action(s) are dispathed
  loadBranchData()
    .then(() => {
      // Setup React-Router server-side rendering
      const routerContext = {};
      const htmlContent = renderToString(
        <Provider store={store}>
          <StaticRouter location={req.url} context={routerContext}>
            <App />
          </StaticRouter>
        </Provider>,
      );

      // Check if the render result contains a redirect, if so we need to set
      // the specific status and redirect header and end the response
      if (routerContext.url) {
        res.status(301).setHeader('Location', routerContext.url);
        res.end();

        return;
      }

      // Checking is page is 404
      const status = routerContext.status === '404' ? 404 : 200;

      // Pass the route and initial state into html template
      res.status(status).send(renderHtml(store, htmlContent));
    })
    .catch((err) => {
      res.status(404).send('Not Found :(');

      console.error(`==>   Rendering routes error: ${err}`);
    });
});



//----------------------------------------------------

//GET ARTICLES
app.get('/api/articleList', (req, res) => {

  console.log('yoyoyo');
    var indexLimit = parseInt(req.query.indexLimit, 10);
    var articleId = req.query.articleId
    var articles = [];

    db.collection('articles')
        .find()
        .sort("dateAdded", -1)
        .limit(indexLimit)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });
});


//------------------------------------


//connect to mongo db
var db
const MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://##CHANGED###:test@ds123930.mlab.com:###/###', (err, database) => {
    if (err) return console.log(err);
    db = database
    console.log('db connected');
})



if (port) {
  app.listen(port, host, (err) => {
    if (err) console.error(`==>   OMG!!! ${err}`);

    console.info(chalk.green(`==>   Listening at http://${host}:${port}`));
    // Open Chrome
    require('../tools/openBrowser').default(port);
  });
} else {
  console.error(chalk.red('==>   OMG!!! No PORT environment variable has been specified'));
}

1 个答案:

答案 0 :(得分:2)

您需要移动上面的/api路线:

app.get('*', (req, res) => {
    ...
}

您对/api/articleList的致电击中了抓住&#39; *&#39;的所有路线处理程序并使用呈现的页面响应请求。在与api进行数据通信时,您不希望页面呈现,您希望来自api的响应:)

中间件按照从上到下的顺序执行。