简体   繁体   中英

cross origin request blocked by cors

I've build a react app connected to node server when i deployed my server and database(not frontend app) using heroku i started getting an error by cors policy saying that "Access to fetch at ' https://my-server-url.herokuapp.com/register ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

i've tried some random things but nothing worked please help me with this here is my server code

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const bcrypt = require('bcrypt');
const register = require('./Controllers/register');
const signIn = require('./Controllers/signIn');
const Image = require('./Controllers/image');

var db = require('knex')({
client: 'pg',
connection: {
connectionString : process.env.DATABASE_URL,
ssl: true
}
});


const app = express();



app.use(cors())
app.use(bodyParser.json());

app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');

});

app.get('/', (req, res) => res.send('working'))
app.post('/signin', (req, res) => {signIn.handleSignIn(req, res, db, bcrypt)})
app.post('/register', (req, res) => {register.handleRegister(req, res, db, bcrypt)})
app.put('/image', (req, res) => {Image.handleImage(req, res, db, bcrypt)})


app.listen(process.env.PORT || 3001, () => console.log(`App listening on ${process.env.PORT}`));

and here is where i am making the request

import React from 'react';

import '../SignIn/SignIn.css';

class Register extends React.Component {

constructor(props){
    super(props)
    this.state = {
        email: '',
        password: '',
        name: ''
    }
}


onEmailChange = (event) => {
    this.setState({email: event.target.value})
}

onPasswordChange =  (event) => {
    this.setState({password: event.target.value})
}

onNameChange =  (event) => {
    this.setState({name: event.target.value})
}

onRegister = () => {
    fetch('https://my-server-url.herokuapp.com/register', {
        method: 'post',
        headers: {'content-type': 'application/json'},
        body: JSON.stringify({
            email: this.state.email,
            password: this.state.password,
            name: this.state.name
        })
    }).then(res => res.json())
      .then(user => {
          if(user.id) {
            this.props.loadUser(user)
            this.props.RouteChange('home');
          }
      })
}



render() {
return(
    <div className='main2'>
        <h2>Register</h2>

        <label className='label'>Name</label>
        <input onChange={this.onNameChange} className='input' type='name'/>

        <label className='label'>Email</label>
        <input onChange={this.onEmailChange} className='input' type='email'/>

        <label className='label'>Password</label>
        <input onChange={this.onPasswordChange} className='input' 
type='Password'/>

        <button onClick={this.onRegister}>Register</button>

    </div>
);
}
}

export default Register;

here is the register request handler

const handleRegister = (req, res, db, bcrypt) => {
const { name, email, password } = req.body;

if(!email || !name || !password){
    return res.status(400).json('incorrect form submission')
}

const saltRounds = 10;

const salt = bcrypt.genSaltSync(saltRounds);

const hash = bcrypt.hashSync(password, salt)

db.transaction(trx => {
  trx.insert({
        hash: hash,
        email: email
    }).into('login')
    .returning('email')
    .then(loginEmail => {
        return trx('users')
        .returning('*')
        .insert({
            name: name,
            email: loginEmail[0],
            joined: new Date()
        })
        .then(user => {
            res.json(user[0])
        }).catch(err => res.json(err))
    })
    .then(trx.commit)
    .catch(trx.rollback)
})


}

module.exports = {
handleRegister: handleRegister
};

You can try to enable a specific route and check:

app.get('/', cors(), (req, res) => res.send('working'))
app.post('/signin', cors(), (req, res) => {signIn.handleSignIn(req, res, db, bcrypt)})
app.post('/register', cors(),(req, res) => {register.handleRegister(req, res, db, bcrypt)})
app.put('/image', cors(), (req, res) => {Image.handleImage(req, res, db, bcrypt)})

By default, Heroku will install all dependencies listed in package.json under dependencies and devDependencies.

After running the installation and build steps Heroku will strip out the packages declared under devDependencies before deploying the application.

It could be that your some of your packages are in devDependencies instead of dependencies and so your code execution at server side is failing?

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