尝试使用CORS
代替package.json
代理人。我记得当我使用它时遇到了随机/间歇性连接问题。简而言之:前端在端口上运行3000
and express
API 运行于5000
。编译后,两者都运行在5000
and express
为编译后的前端js提供服务,其作用类似于API。
设置非常相似,但没有连接问题:
快递服务器package.json
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "NODE_ENV=production node app.js",
"server": "NODE_ENV=development nodemon app.js",
"client": "npm run start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"seeds": "NODE_ENV=development node seeds.js"
},
...
客户端/package.json(使用 sass 编译器,您可以使用/忽略)。
...
"scripts": {
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
...
客户端/src/actions/axiosConfig.js(然后我创建一个axios
配置自动指向我运行的 Express API5000
)
import axios from 'axios';
export const app = axios.create({
baseURL: 'http://localhost:5000/api/',
withCredentials: true
})
客户端/src/actions/authActions.js(然后导入axios
config)
import { app } from './axiosConfig';
const signinUser = props => dispatch => (
app.post(`signin`, { ...props })
.then(({data}) => {
dispatch({ type: types.SET_SIGNEDIN_USER, payload: data })
dispatch(fetchAvatarOnLogin());
})
.catch(err => dispatch({ type: types.SERVER_ERROR, payload: err }))
);
快递服务器.js (I use consign
导入所有文件):
const express = require('express');
const app = express();
const consign = require('consign');
consign({ locale: 'en-us', verbose: false})
.include('libs/middlewares.js')
.then("database")
.then("shared")
.then("services")
.then("controllers")
.then("routes")
.then('libs/server.js')
.into(app);
然而,等价的是:
// APP REQUIRED IMPORTS
const express = require('express');
const app = express();
...etc
// APP MIDDLEWARES
...
app.use(cors({credentials: true, origin: http://localhost:3000})) // allows receiving of cookies from front-end
app.use(morgan('tiny')); // logging framework
app.use(bodyParser.json()); // parses header requests (req.body)
app.use(bodyParser.urlencoded({ extended: true })); // allows objects and arrays to be URL-encoded
...etc
// DATABASE CONFIG/CONN
// APP SHARED FUNCS
// APP SERVICES (passport, sendgrid mailer, ...etc)
// APP CONTROLLERS
...
signin: (req, res, done) => passport.authenticate('local-login', err => (
(err || !req.session) ? sendError(err || badCredentials, res, done) : res.status(201).json({ ...req.session }))
)(req, res, done)
...etc
// APP ROUTES
...
app.post('/api/signin', signin);
...etc
// EXPRESS SERVER
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
app.get('*', (req, res) => res.sendFile(path.resolve('client', 'build', 'index.html')));
}
app.listen(5000);