gpt4 book ai didi

javascript - Axios 到 Node (Express)GET 请求

转载 作者:行者123 更新时间:2023-12-01 03:21:04 24 4
gpt4 key购买 nike

因此,使用 axios,我尝试向我的 Express 服务器发出请求,这是我的 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;
};

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

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

它不会记录“hello”,也不会显示任何错误,我只是认为我缺少 Axios 到达我的服务器的某些内容...

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

NOTE: the Axios request works fine when the "API_URL" variable is set to a myjson url link, so I know my action works fine, I just feel like I'm missing something for it to reach my server

编辑:请查看我的整个 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'));
}

最佳答案

您需要将 /api 路由移到上面:

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

您对 /api/articleList 的调用正在捕获“*”的所有路由处理程序,并使用呈现的页面响应请求。当与您的 api 进行数据通信时,您不需要页面呈现,您需要来自 api 的响应:)

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

关于javascript - Axios 到 Node (Express)GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45195808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com