Ada*_*ite 4 javascript express reactjs
我有一个React应用程序,该应用程序通过API从单独的数据库中提取数据。
在本地运行时,该应用程序是一个端口,而API在另一个端口上。
由于当我在应用程序中对API进行AJAX调用时,我需要包含API可以连接的URL。
如果我对单独的端口进行硬编码(例如,该应用程序位于http:// localhost:3000上,而API则位于http:// localhost:3100上),则可以使用AJAX url调用API http:// localhost:3100 / api / trusts)。
但是,由于应用程序和API位于不同的端口上,因此我无法将AJAX网址设为相对路径,因为它错误地将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}`);
});
Run Code Online (Sandbox Code Playgroud)
下面是我试图使之无效的AJAX调用,因为相对路径附加到应用程序的端口(即http:// localhost:3000 /)而不是API的端口(即http://)本地主机:3100 /):
axios.get("/api/trusts")
.then(res => {
this.setState({trusts: res.data});
})
.catch(console.error);
Run Code Online (Sandbox Code Playgroud)
要告诉开发服务器将任何未知请求代理到开发中的API服务器,请在package.json中添加一个代理字段,例如:
"proxy": "http://localhost:4000",
这样,当您
fetch('/api/todos')进行开发时,开发服务器将识别出它不是静态资产,并将您的请求http://localhost:4000/api/todos作为后备代理。开发服务器将仅尝试发送请求,而不发送text/html其Accept标头中的内容到代理。
“请记住,代理仅在开发中起作用(从npm start开始),并且由您来确保/ api / todos之类的URL指向生产中的正确对象。”
注意:此功能在react-scripts@0.2.3及更高版本中可用。
此处有更多详细信息:https : //github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development
| 归档时间: |
|
| 查看次数: |
3864 次 |
| 最近记录: |