最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Configuring CORS with express and making requests on the front end with axios - Stack Overflow

programmeradmin5浏览0评论

I'm trying to get a JSON object from one of my sever routes using axios in a react ponent.

Here's the relevant server code

var express = require('express')
var app = express()

app.use(require('morgan')('bined'))
app.use(require('cookie-parser')())
app.use(require('body-parser').urlencoded({ extended: true }))
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }))

app.use(passport.initialize())
app.use(passport.session())

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, next) {
    res.send(req.user)
  }
)
app.listen(process.env.PORT || 8080)

And here is the relevant axios function request in my ponent

 getUser () {
    axios.get('http://localhost:8080/', {mode: 'cors', 'Cache-Control': 'no-cache'})
      .then(res =>
        res.data
      )
      .then(user =>
        this.setState({
          user: user
        })
      )
      .catch(console.error())
  }

This code works if I disable Cross-Origin Restrictions in browser development settings (I receive the correct JSON object), but it doesn't work by default as it should. I've tried using this CORS express middleware, manually setting the header mode to "cors" instead of "no-cors", setHeader instead of header in the res.header section, adding 'Access-Control-Allow-Origin' and related headers to my axios request and more. I'm unsure how to fix this issue.

When I don't disable Cross-Origin-Restriction in browser I only ever receive an empty string response, no headers set except sometimes 'content-type' and I receive no error message telling me anything. It goes through with the exact same status code as if it were responding correctly.

I'm trying to get a JSON object from one of my sever routes using axios in a react ponent.

Here's the relevant server code

var express = require('express')
var app = express()

app.use(require('morgan')('bined'))
app.use(require('cookie-parser')())
app.use(require('body-parser').urlencoded({ extended: true }))
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }))

app.use(passport.initialize())
app.use(passport.session())

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, next) {
    res.send(req.user)
  }
)
app.listen(process.env.PORT || 8080)

And here is the relevant axios function request in my ponent

 getUser () {
    axios.get('http://localhost:8080/', {mode: 'cors', 'Cache-Control': 'no-cache'})
      .then(res =>
        res.data
      )
      .then(user =>
        this.setState({
          user: user
        })
      )
      .catch(console.error())
  }

This code works if I disable Cross-Origin Restrictions in browser development settings (I receive the correct JSON object), but it doesn't work by default as it should. I've tried using this CORS express middleware, manually setting the header mode to "cors" instead of "no-cors", setHeader instead of header in the res.header section, adding 'Access-Control-Allow-Origin' and related headers to my axios request and more. I'm unsure how to fix this issue.

When I don't disable Cross-Origin-Restriction in browser I only ever receive an empty string response, no headers set except sometimes 'content-type' and I receive no error message telling me anything. It goes through with the exact same status code as if it were responding correctly.

Share Improve this question edited Feb 18, 2018 at 18:37 Rikku 4386 silver badges14 bronze badges asked Feb 18, 2018 at 6:06 danraybernarddanraybernard 533 silver badges7 bronze badges 1
  • Install CORS middle ware it should work npm install cors – Mahesh G Commented Feb 18, 2018 at 7:31
Add a ment  | 

1 Answer 1

Reset to default 5

Install the cors middleware at npm

This code then will enable all CORS requests.

var express = require('express');
var cors = require('cors');
var app = express();

app.use(cors());
发布评论

评论列表(0)

  1. 暂无评论