heroku 当请求的凭据模式为“include”时,响应中的“Access-Control-Allow-Origin”标头不能为通配符“*”

llew8vvj  于 2022-11-13  发布在  其他
关注(0)|答案(2)|浏览(232)

我尝试将我的电子应用程序转换为全web。当我从我的localhost运行应用程序时,我得到这个错误:
无法加载https://agrt.herokuapp.com/login:对预检请求的响应未通过访问控制检查:当要求的证明数据模式为'include'时,回应中的'Access-Control-Allow-Origin'信头值不能是万用字符'*'。因此不允许来源'http://localhost:4200'。XMLHttpRequest起始之要求的证明数据模式是由withCredentials属性控制。
在我的客户端上,我发送了一个http请求,其中包含:

this.http.post(Consts.REMOTE_URL + '/login', {
      username: username,
      password: password
    }, {withCredentials:true}).

在我的服务器上我使用cors ant我设置:

app.use(function(req,res,next){
        res.header("Access-Control-Allow-Origin","http://localhost:4200");
        res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Accept');
        res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
        res.header('Access-Control-Allow-Credentials', true);
        next();
    })

我的服务器在Heroku上
当我逃离电子时一切都很顺利。
拜托,任何帮助都是最好!
服务器.js:

const express = require('express')
const passport = require('passport')
const winston = require('winston')
const db = require('./db')
const cors = require('cors')
require('dotenv').config()

const port = process.env.PORT || 9000
const app = express()

app.use(cors())
require('./config/passport')(passport, db)
require('./config/express')(app, passport, db.pool, db)
require('./app/routes')(app, passport)

app.use(function (err, req, res, next) {
  if (err.message && (~err.message.indexOf('not found'))) {
    return next()
  }
  winston.error(err.stack)
  return res.status(500).json({error: 'Error on backend occurred.'})
})

const server = app.listen(port, () => {
  console.log("listening to port: "+port);
  if(app.get('env') === 'test') return

  winston.log('Express app started on port ' + port)
})

server.on('close', () => {
  winston.log('Closed express server')

  db.pool.end(() => {
    winston.log('Shut down connection pool')
  })
})

Express.JS:

const path = require('path')
const express = require('express')
const expressHandlebars = require('express-handlebars')
const expressValidator = require('express-validator')
const session = require('express-session')
const pgSession = require('connect-pg-simple')(session)
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const methodOverride = require('method-override')
const morgan = require('morgan')
const winston = require('winston')
const config = require('./')
const resumable = require('../app/lib/resumablejs')
const env = process.env.NODE_ENV || 'development'

module.exports = (app, passport, pool, db) => {
    let log = 'dev'
    if (env !== 'development') {
    log = {
      stream: {
        write: message => winston.info(message)
      }
    }
  }

    if (env !== 'test') app.use(morgan(log))

    app.engine('handlebars', expressHandlebars())
    app.set('view engine', 'handlebars')

    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({ extended: true }))
    app.use(expressValidator())

    app.use(methodOverride(function (req) {
        if (req.body && typeof req.body === 'object' && '_method' in req.body) {
            var method = req.body._method
            delete req.body._method
            return method
        }
    }))

    app.use(cookieParser())
    app.use(session({
        store: new pgSession({
            pool
        }),
        secret: config.session_secret,
        // saveUninitialized: false,
        // resave: false,
         cookie: { maxAge: 14 * 24 * 60 * 60 * 1000 }
    }))

    /////////////////////////////////////////
    app.use(function(req,res,next){
        res.header("Access-Control-Allow-Origin","http://localhost:4200");
        res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Accept');
        res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
        res.header('Access-Control-Allow-Credentials', true);
        next();
    })
    //////////////////////////////////////////

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

    app.use('/', express.static(path.join(config.root, 'public')))
    app.use('/files', resumable(undefined, undefined, db))
}
g6baxovj

g6baxovj1#

请尝试使用以下配置:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Credentials", true);
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
  res.header(
    "Access-Control-Allow-Headers",
    "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept"
  );
  if ("OPTIONS" == req.method) {
    res.send(200);
  } else {
    next();
  }
});
bfhwhh0e

bfhwhh0e2#

或者 , 如果 您 使用 CORS 中间 件 , 并 希望 发送 withCredentials 布尔 值 为 true ( 例如 , 发送 带有 set-cookie 标 头 的 响应 ) , 则 可以 如下 配置 CORS :

const corsOptions = {
  origin: ["http://localhost:3000"],
 //update: or "origin: true," if you don't wanna add a specific one
  credentials: true,
};
app.use(cors(corsOptions));

中 的 每 一 个

  • 如果 使用 凭据 app . use ( corse ( ) ) 将 不 起 作用 , 您 应该 在 corsOptions 中 指定 您 的 特定 来源 。

它 ( 在 某种 程度 上 ) 等于 如下 设置 响应 头 :

app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");
  res.header("Access-Control-Allow-Credentials", true);
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  next();
});

格式

相关问题