Skip to content
Advertisement

CORS Policy blocking my API requests in a google cloud platform app engine in a live website

I uploaded my node js server to the google cloud app engine service to be able to make the front end work. I also uploaded the frontend and my website is now live.

The node js is running fine and it’s deployed in the app engine in google cloud.

my only problem is that whenever I try to make a request I get blocked by the cors policy which I looked everywhere for a solution but could not find any.

here is what the error looks like exactly in my console:

Access to XMLHttpRequest at 'https://vocal-byte-324123.de.r.appspot.com/login' 
from origin 'https://mywebiste.org' has been blocked by CORS policy: The value of the 
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
when the request's credentials mode is 'include'. The credentials mode of requests 
initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

What am I supposed to do to get rid of this error?

Here is what I am doing

index.js from my node js server

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const multer = require('multer');
const path = require('path');
const request = require('request');

const app = express();

const db = mysql.createPool({
    host: "127.0.0.1",
    user: "xxx",
    password: "xxx",
    database:"xxx" 
});

//Middleware 
app.use(cors({
    origin:["https://mywebsite.org"],
    method:["GET","POST","OPTIONS","PUT"],
    credentials: true,
}));
app.options('*', cors());

app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(session({
    key: "userID",
    secret: "",
    resave: false,
    saveUninitialized: false,
    cookie: {
        expires: 3600 * 1000 * 24 * 365 * 10,
    },
}))

app.use('/', express.static(path.join(__dirname, '/')));

//Log In User API
app.post('/api/login', (req, res) => {

    const email = req.body.email
    const password = req.body.password
    db.query("SELECT * FROM users WHERE email = ? and password = ?", [email,password], (err, result) => {

        if(err){
            console.log(err);
            res.send({err:err});
        }

        if(result.length > 0){
            
            req.session.user = result;
            
            res.send(result)

        }else{
            res.send({message:"Wrong username or password"})
         }
    });
});

//Fetch Logged in User Info, and Save a Session
app.get("/login", (req, res) => {
    if(req.session.user){
        res.send({loggedIn: true, user: req.session.user})
    }else{
        res.send({loggedIn: false})
    }
})



//Start the Server
app.listen(8080,() => {console.log("running on port 3001")});

And in the frontend i am requesting like this:

// this is the URL of where my node js server lies https://vocal-byte-324123.de.r.appspot.com
const loginUser = () => {
      
            Axios.post('https://vocal-byte-324123.de.r.appspot.com/api/login',{
                email: email, 
                password:password,
              }).then((response) => {
                  
                if(response.data.message){
                    alert("Incorrect email or password");
                }else{
                  //  alert("Logged In Successfully");
                    history.push("/Home");
                    window.location.reload();
                }   
            });
        }

Any help, please?

EDIT:

tried Simit answer it does not work aswell.

Advertisement

Answer

Try this middleware on top of your routes…

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "OPTIONS, GET, POST, PUT, PATCH, DELETE"
  );
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

Hope this works for you…

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement