表示app.get('/ *')和api CORs问题

你能告诉我如何让我的JSON API?

server.js

app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }) app.get('/api', function(req, res) { res.header() res.json({'message' : 'hi this is my json obj'}); }) 

App.js

 class App extends React.Component { componentDidMount() { // let foo; axios.get('http://localhost:3000/api') .then(res => { console.log(res.data); res.data.message; }) .catch(err => { console.log(err); }) } 

出于某种原因,就像我可以得到反应路由器访问本地主机:3000 /仪表板很好,通过inputurl字段。 它是不断返回的HTMLstring。 我可以改变什么,以便我可以接收json对象而不是htmlstring?

你有Cors问题,因为你试图从这个urlhttp:// localhost:3000 / api检索数据,这是很正常的。 问题是,如果你从另一台服务器上提供你的应用程序(让我们假设Apache为80端口),你也有问题,这是正常的。

避免这种情况的一种方法是在注册所有路由之前注册一个中间件:

 app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.get('/*', function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }) app.get('/api', function (req, res) { res.header() res.json({ 'message': 'hi this is my json obj' }); }) 

而不是创build自己的中间件,你可以使用Cors模块并注册它:

 var cors = require('cors'); app.use(cors()); 

要知道,做这样的事情:

 res.header("Access-Control-Allow-Origin", "*"); 

可能对你的服务器有点危险,因为其他应用程序将能够直接从浏览器使用你的api而没有问题。 有一个原因,Cors已经到位,我会build议研究一下。

编辑

顺便说一下,如果你从同一个节点服务器提供api和你的应用程序,那么只需要replace这个:

 axios.get('http://localhost:3000/api') 

与这一个:

 axios.get('/api') 

应该pipe用

您需要切换路由声明的顺序:

 app.get('/api', function(req, res) { res.header() res.json({'message' : 'hi this is my json obj'}); }) app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }) 

这是因为/*也会匹配/api ,并且Express根据哪条路线匹配得最好而不匹配,但哪条路线首先匹配。

始终在不太具体的路线之前申报更具体的路线。