表达app.get (& # 39;/* ')和api CORs问题

express app.get(' /* ') and api CORs issue

本文关键字:api 问题 CORs app 表达 get      更新时间:2023-09-26

你能告诉我如何得到我的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);
    })
  }

由于某种原因,我可以通过输入url字段让react路由器访问localhost:3000/dashboard。它一直返回html字符串。我能改变什么,使它,使我可以接收json对象,而不是html字符串?

您有cors问题,因为您试图从此url http://localhost:3000/api检索数据,这是很正常的。问题是,如果您从另一台服务器(让我们假设apache的端口为80)提供应用程序,那么您也会遇到cors问题。

绕过这个的一种方法是在注册所有路由之前注册一个中间件:
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' });
})

您可以使用cors模块并像这样注册它,而不是创建自己的中间件:

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

注意做这样的事情:

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

对于您的服务器来说可能有点危险,因为其他应用程序将能够毫无问题地直接从浏览器使用您的API。这是有原因的,我建议研究一下。

编辑

顺便说一下,如果你的api和react应用程序来自同一个节点服务器,那么只需替换这一个:

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

和这个:

axios.get('/api')

应该

你需要改变路由声明的顺序:

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的匹配不是基于哪条路由匹配最好,而是基于哪条路由首先匹配

总是在不太具体的路由之前声明更具体的路由