如何正确提供要用作移动应用程序端点的JSON?
当前,我正在这样做-这是 app.js (快速):
const PORT = process.env.PORT || 5000;
const env = process.env.NODE_ENV || 'development';
const express = require('express'),
path = require('path'),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
passport = require('passport');
const config = require('./backend/config/db')[env]; // load db
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
const app = express();
const apii = require('./backend/routes/apii');
// Serve static files from the React app -- added because of Heroku, the local app doesn't need this
app.use(express.static(path.join(__dirname, 'frontend/build')));
app.use(passport.initialize());
require('./backend/passport')(passport);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// routes
app.use('/apii', apii);
//
app.get('*', function(request, response) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//response.sendFile(path.resolve(__dirname, './frontend/build', 'index.html'));
response.sendFile(path.resolve(__dirname, '../', 'frontend/build/index.html'));
});
app.listen(PORT, () => {
console.log(`Server is running on PORT ${PORT}`);
});
module.exports = app;
这是 ./ backend / routes / apii.js :
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
var testObject = {
"AppName": "MongoPop",
"Version": 1.0
}
res.json(testObject);
});
module.exports = router;
当前,我以这种方式呈现JSON数据(作为移动应用程序的端点)-在ReactJS路由中,我具有:
<Route exact path="/apii" component={ ApiV1 } />
,然后在 ApiV1 组件中,进行以下操作:
import React, { Component } from 'react';
import axios from 'axios';
export default class ApiV1 extends Component {
constructor() {
super();
this.state = {
events: ''
}
}
componentDidMount() {
axios.get('/apii')
.then((response) => {
this.setState({events: response.data.placeholder});
console.log('I got JSON data! ', this.state.placeholder);
}).catch(err => {
console.log('CAUGHT IT! -> ', err);
});
}
render() {
return (
<div><pre>{JSON.stringify(this.state.placeholder, null, 2) }</pre></div>
)
}
}
我已经将JSON呈现给ReactJS组件,感觉不对。
我曾尝试在Express路由上提供此JSON文件,但是该路由从未在3000(ReactJS)端口上访问- localhost:3000 / apii 这给了我空白页。在 localhost:5000 / apii -Express路由上,可以访问数据,但是我无法从移动应用程序访问此终结点。
我在项目的前端使用代理:
"proxy": "http://localhost:5000"
它适用于React app + Express后端,该网站运行良好,但是它没有托管/apii
端点-这里的结果只是空白页面。
如何正确提供JSON端点?