简体   繁体   中英

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

can you tell me how I can get my 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);
    })
  }

For some reason, like that I can get react router to access localhost:3000/dashboard just fine by inputing the url field. It is keep returning html string. what can i change to make it so that I can receive json object instead of html string?

You have cors issue because you are trying to retrieve the data from this url http://localhost:3000/api and this is quite normal. The thing is that if you serve your application from another server (let's assume port 80 for apache) it is normal that you have the cors problem as well.

One way to bypass this is by registering a middleware before registering all your routes:

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' });
})

Instead of creating your own middlewares you can use the cors module and register it like that:

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

be aware that doing something like that:

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

can be a bit dangerous for your server, because other applications will be able to use your api directly from the browser without a problem. There is a reason that cors are in place and I would suggest to study about it.

EDIT

By the way, if you serve your api and your react application from the same node server then just by replacing this one:

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

with this one:

axios.get('/api')

should work

You need to switch the order of route declaration:

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'));
})

That's because /* will also match /api , and Express doesn't match based on which route matches best , but which route matches first .

Always declare more specific routes before less specific routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM