我有一个 React 应用程序,它通过 API 从单独的数据库中提取数据。
当我在本地运行它时,应用程序是一个端口,API 在另一个端口上。
因为当我在应用程序中对 API 进行 AJAX 调用时,我需要包含 API 可以连接的 URL。
如果我对单独的端口进行硬编码(例如,应用程序在 http://localhost:3000 上,API 在 http://localhost:3100 上,使 AJAX url 调用 API http://localhost:3100/api/trusts )。
但是,由于应用程序和 API 在不同的端口上,我无法将 AJAX url 设为相对路径,因为它错误地将 AJAX 调用发送到 http://localhost:3000/api/trusts而不是 http://localhost:3100/api/trusts .
如何让它们在同一个端口上运行?
谢谢!
这是我的 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:3000/ )而不是 API 的端口(即 http://localhost:3100/ ):
axios.get("/api/trusts")
.then(res => {
this.setState({trusts: res.data});
})
.catch(console.error);
最佳答案
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:
"代理": "http://localhost:4000",
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 指向生产中的正确内容。”
注意:此功能适用于 react-scripts@0.2.3 及更高版本。
关于javascript - 如何在同一端口上设置 React 应用程序和 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51367424/