没用过azure
之前我也不使用代理(由于其随机连接问题 https://stackoverflow.com/questions/52483349/econnrefused-error-for-create-react-app-and-node-server),但是如果你的应用程序基本上正在运行express
,你可以利用cors https://github.com/expressjs/cors。 (顺便说一下,更常见的做法是在 Express 服务器上运行5000
than 3001
.)
我首先设置了一个环境/config.js文件夹和文件如下:
module.exports = {
development: {
database: 'mongodb://localhost/boilerplate-dev-db',
port: 5000,
portal: 'http://localhost:3000',
},
production: {
database: 'mongodb://localhost/boilerplate-prod-db',
port: 5000,
portal: 'http://example.com',
},
staging: {
database: 'mongodb://localhost/boilerplate-staging-db',
port: 5000,
portal: 'http://localhost:3000',
}
};
然后,根据环境,我可以实施cors
我在其中定义快速中间件:
const cors = require('cors');
const config = require('./path/to/env/config.js');
const env = process.env.NODE_ENV;
app.use(
cors({
credentials: true,
origin: config[env].portal,
}),
);
请注意门户网站和AJAX
请求必须具有匹配的主机名。例如,如果我的应用程序托管在http://example.com
,我的前端 API 请求必须向http://example.com/api/
(not http://localhost:3000/api/
-- 点击这里 https://github.com/mattcarlotta/Matts-Universe/blob/development/client/src/actions/axiosConfig.js看看我如何在我的网站上实现它),以及portal
env 必须与主机名匹配http://example.com
。在运行多个环境时,这种设置是灵活且必要的。
或者如果您正在使用create-react-app
,然后只需弹出您的应用程序并实施proxy https://webpack.js.org/configuration/dev-server/#devserver-proxy在 - 的里面webpack
生产配置。
或者将您的应用程序迁移到我的全栈样板 https://github.com/mattcarlotta/Webpack-React-Boilerplate/tree/fullstack,它实现了cors
上面的例子。