如何在同一端口上设置React应用程序和API? [英] How to set React app and API on same port?
问题描述
我有一个React应用程序,该应用程序通过API从单独的数据库中提取数据.
I've got a React app that via an API pulls data from a separate database.
当我在本地运行它时,该应用程序是一个端口,而API在另一个端口上.
When I run it locally, the app is one port and the API is on another port.
自从我在应用程序中对API进行AJAX调用后,我需要包含API可以连接的URL.
Since when I make AJAX calls in the app to the API, I need to include the URL where the API can connect.
如果我对单独的端口进行硬编码(例如,该应用程序位于 http://localhost:3000 上并且 http://localhost:3100 上的API,从而对API
It works if I hardcode the separate port (e.g., the app is on http://localhost:3000 and the API on http://localhost:3100, making the AJAX url call to the API http://localhost:3100/api/trusts).
但是,由于应用程序和API位于不同的端口上,因此我无法将AJAX网址设为相对路径,因为它错误地将AJAX调用发送到 http://localhost:3000/api/trusts 而不是 http://localhost:3100/api/trusts .
However, since the app and API are on different ports, I can't make the AJAX url a relative path because it erroneously sends the AJAX call to http://localhost:3000/api/trusts and not http://localhost:3100/api/trusts.
如何让它们在同一端口上运行?
How do I get them to run on the same port?
谢谢!
这是我的server.js:
Here's my server.js:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//set our port to either a predetermined port number if you have set it up, or 3001
var port = process.env.PORT || 5656;
//db config
var mongoDB = 'mongodb://XXX:XXX!@XXX.mlab.com:XXX/XXX';
mongoose.connect(mongoDB);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//body parsing
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// allow cross-browser
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
});
// handling static assets
app.use(express.static(path.join(__dirname, 'build')));
// api handling
var TrustsSchema = new Schema({
id: String,
name: String
});
var Trust = mongoose.model('Trust', TrustsSchema);
const trustRouter = express.Router();
trustRouter
.get('/', (req,res) => {
Trust.find(function(err, trusts) {
if (err) {
res.send(err);
}
res.json(trusts)
});
});
app.use('/api/trusts', trustRouter);
//now we can set the route path & initialize the API
router.get('/', function(req, res) {
res.json({ message: 'API Initialized!'});
});
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
下面是我要进行的AJAX调用不起作用,因为相对路径已附加到应用程序的端口(即 http://localhost:3100) /):
Below is the AJAX call I'm trying to make that doesn't work because the relative path is appended to the app's port (i.e., http://localhost:3000/) and not the API's port (i.e., http://localhost:3100/):
axios.get("/api/trusts")
.then(res => {
this.setState({trusts: res.data});
})
.catch(console.error);
推荐答案
要告诉开发服务器将任何未知请求代理到开发中的API服务器,请在您的package.json中添加一个代理字段,例如:
To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:
"proxy": "http://localhost:4000",
这样,当您在开发中
fetch('/api/todos')
时,开发服务器将识别出它不是静态资产,并将您的请求代理到http://localhost:4000/api/todos
作为备用.开发服务器将仅尝试将Accept
标头中没有text/html
的请求发送到代理.
This way, when you
fetch('/api/todos')
in development, the development server will recognize that it’s not a static asset, and will proxy your request tohttp://localhost:4000/api/todos
as a fallback. The development server will only attempt to send requests withouttext/html
in itsAccept
header to the proxy.
请记住,代理仅在开发中起作用(从npm start开始),并且由您来确保/api/todos之类的URL指向生产中的正确对象."
"Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production."
注意:此功能在react-scripts@0.2.3及更高版本中可用.
More details here: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development
这篇关于如何在同一端口上设置React应用程序和API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!