跨域请求被阻止:同源策略不允许在 https://localhost:8000/users/login 读取远程资源

Posted

技术标签:

【中文标题】跨域请求被阻止:同源策略不允许在 https://localhost:8000/users/login 读取远程资源【英文标题】:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8000/users/login 【发布时间】:2021-08-04 02:42:22 【问题描述】:

我正在尝试向 /users/signup 端发布消息,并且每次都会发生此错误。 这是我的 server.js 代码

const https = require('https');
const fs = require('fs');
var path = require('path');
const  mongoose = require('mongoose');
const express = require('express');
var cors = require('cors') //
var session = require('express-session');
var FileStore = require('session-file-store')(session); // data base for storing information about sessions.
var cookieParser = require('cookie-parser');
var logger = require('morgan'); // gia ta htpp errors, requests logger
mongoose.set('useFindAndModify', false);
mongoose.set('useUnifiedTopology',true);
const url = 'mongodb://localhost:27017/database';
mongoose.set('useNewUrlParser',true);
mongoose.set('useCreateIndex',true);
mongoose.connect(url)

.then(connection => 
  console.log('Connected to MongoDB DB')
)
.catch(error => 
console.log(error.message)
)
var app = express();
app.use(cors());
var passport = require('passport');
var authenticate = require('./authenticate');
const usersRouter = require('./routes/users');
const options = 
  key: fs.readFileSync('./key.pem','utf8'),
  cert: fs.readFileSync('./server.crt','utf8')
;

app.use(function(req, res, next)  // kolpa magkiorika poy de ta kserw
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Headers, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, PATCH, OPTIONS');
    next();
);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded( extended: false ));

app.use(session(
  name: 'session-id',
  secret: '12345-67890-09876-54321', // digital sign for cookie.( Server secret key to sign the cookie)
  saveUninitialized: false,
  resave: false,
  store: new FileStore((logFn: function()))
));
app.use(passport.initialize());
app.use(passport.session());

app.use('/users',usersRouter);

function auth (req, res, next) 
  if (!req.user) 
    var err = new Error('You are not authenticated!');
    err.status = 403;
    return next(err);
  
  else 
        next();
  

app.use(auth);
const port = 8000;
server = https.createServer(options, app).listen(port, function()
    console.log(`Server started on port $port`);
);
 //error  handler 
module.exports = server;

我添加了几行代码以允许对请求进行 cors,但错误仍然存​​在。当我使用邮递员时,一切正常,并且 cors 标头位于响应标头中。

这里是注册组件

import React,  Component,useState  from 'react';
import '../css/Register.css';
import axios from 'axios';
import withRouter from 'react-router';
import url from '../services/url';

class Register extends Component
    constructor(props)
        super(props);
        this.state = 
            username: "",
            password: "",
            password2: "",
            phone: "",
            email: "",
            userType: ""
        ;
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    

    handleChange(event) 
        this.setState( [event.target.name]: event.target.value )
    

    handleSubmit = async event => 
      event.preventDefault();
        
        if(this.state.password === this.state.password2)
            try 
                const response = await fetch(`https://localhost:8000/users/signup`, 
                    method: 'POST',
                    mode: 'cors',
                    headers: 
                        'Content-Type': 'application/json',
                    ,
                    body: JSON.stringify(
                        username: this.state.username,
                        password: this.state.password,
                        phone: this.state.phone,
                        email: this.state.email,
                        userType: this.state.userType

                    )
                )
                const jsoned = await response.json();
             catch (error) 
                console.log(error);
                console.log('asdfasfasfa');
            
        else
            alert('passwords do not match')
            
  ;
render()
      .... html code..
    
export default withRouter(Register);

以及完整的错误信息

跨域请求被阻止:同源策略不允许读取位于 https://localhost:8000/users/signup 的远程资源。 (原因:CORS 请求未成功)。 TypeError:尝试获取资源时出现 NetworkError。

注册路线。

router.post('/signup', (req, res, next) => 
  User.register(new User(username: req.body.username, email:req.body.email, phone:req.body.phone, userType:req.body.userType), 
    req.body.password, (err, user) => 
    if(err) 
      console.log(err)
      res.statusCode = 500;
      res.setHeader('Content-Type', 'application/json');
      res.json(err: err);
    
    else 
      passport.authenticate('local')(req, res, () => 
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(success: true, status: 'Registration Successful!');
      );
    
  );
);

我发送 post 请求时的请求标头

OPTIONS /users/signup HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:3000/
Origin: http://localhost:3000
Connection: keep-alive

【问题讨论】:

我刚刚在一个类似的问题上发布了这个答案***.com/a/67525153/10789668 您的第二个 app.use 应用 cors 标头应该是不必要的。您可以直接在您的问题中提供完整的 cors 错误吗?查看发送请求以获取完整图片的客户端代码也将有所帮助。 鉴于完整的 cors 错误消息,我怀疑您的用户注册路线引发错误 我不相信这是因为用户/登录端给了我这个错误。 您能在开发工具的网络选项卡中看到请求吗?请求方法和响应码是什么? 【参考方案1】:

我在使用 Mozilla Firefox 访问时遇到了同样的问题。我正在尝试使用this 找到替代方案。我可以通过禁用 Firefox 中的 HTTPS 设置来解决这个问题

请注意,这个问题只发生在火狐浏览器中,所以使用其他浏览器访问时没有问题。

【讨论】:

【参考方案2】:

所以,经过几天的搜索,我发现 Mozzila Firefox 阻止了自签名证书。我不得不为 localhost 添加一个例外。 :)

【讨论】:

【参考方案3】:

尝试将请求发送到 http:// 而不是 https://

【讨论】:

没有任何改变。谢谢大家的时间。

以上是关于跨域请求被阻止:同源策略不允许在 https://localhost:8000/users/login 读取远程资源的主要内容,如果未能解决你的问题,请参考以下文章

跨域请求被阻止:同源策略不允许读取远程资源

跨域请求被阻止:同源策略不允许在 http://........ 读取远程资源

Ajax:跨域请求被阻止:同源策略不允许读取远程资源

跨域请求被阻止:同源策略不允许在 http://localhost3000 读取远程资源

Ajax 跨域请求被阻止:同源策略不允许读取远程资源

跨域请求被阻止:同源策略不允许读取某个 URI 处的远程资源