Search code examples
javascriptnode.jsreactjsexpress

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8000/users/login


I am trying to make a post message to the /users/signup end and this error occurs every time. Here is my code from 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;

I have add lines of code to allow cors on requests but the error keep exists. When i am using postman everything works fine, and the cors headers are in the response headers.

Here it is , the Register Component

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

And the full error message

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8000/users/signup. (Reason: CORS request did not succeed). TypeError: NetworkError when attempting to fetch resource.

the signup route.

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

Request headers when i send post request

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

Solution

  • So, after days of searching , i figured it out that Mozzila Firefox was blocking self signed certificates. I had to add an exception for localhost. :)