Reputation: 217
I have a react app that I'm trying to add a Node/Express/MySQL backend to with OAuth. My React app is hosted on localhost:3000 and the express server is on localhost:4000. I added "proxy":"http://localhost:4000" to the react app's package.json file to send requests to the server. The Authorized Javascript Origin for the OAuth is http://localhost:4000. The Authorized redirect URI is http://localhost:4000/auth/google/redirect.
These are the errors I get in the browser's console when I try to get to the route on the server:
One says No 'Access-Control-Allow-Origin' header is present on the requested resource.
The other says 'Cross-Origin Read Blocking (CORB) blocked cross-origin response....with MIME type text/html.'
I have no clue what I'm doing wrong and I've been stuck since yesterday.
Failed to load https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Fauth%2Fgoogle%2Fredirect&scope=profile&client_id={clientiddeletedbyme}.apps.googleusercontent.com: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Fauth%2Fgoogle%2Fredirect&scope=profile&client_id={iddeletedbyme}apps.googleusercontent.com with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Here is my code in the package.json file for my react app:
{
"name": "workout_tracker",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"firebase": "^5.3.0",
"jw-paginate": "^1.0.2",
"jw-react-pagination": "^1.0.7",
"normalize.css": "^8.0.0",
"random-id": "0.0.2",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-headroom": "^2.2.2",
"react-icons-kit": "^1.1.6",
"react-redux": "^5.0.7",
"react-router-dom": "^4.3.1",
"react-scripts-cssmodules": "^1.1.10",
"react-swipe-to-delete-component": "^0.3.4",
"react-swipeout": "^1.1.1",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"redux-devtools-extension": "^2.13.5"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"proxy":"http://localhost:4000"
}
Here is the code in my react app that sends the request to the server:
express=()=>{
axiosInstance.get("/google").then(res=>{
console.log(res);
}).catch(err=>console.log(err));
}
Here is the code in the server
let express = require("express");
let cors= require("cors");
let mysql = require("mysql");
const util = require("util");
const passportSetup = require("./config/passport-setup");
const passport = require("passport");
let app = express();
let connection =mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "Workout_Tracker",
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
app.use(cors(
{origin:"http://localhost:3000",
credentials:true,
allowHeaders:"Content-Type"
}
));
app.options("/google", cors());
app.get("/google", cors(), passport.authenticate("google",{
scope:['profile']
}));
...omitted a bunch of SQL queries
app.listen(4000, () => console.log("Listening on port 4000!"));
Upvotes: 4
Views: 6801
Reputation: 31
Here is the sample code of a new middleware you need to install to express BEFORE you define any routes:
const cors = require('cors');
app.use('*', function(req, res, next) {
//replace localhost:8080 to the ip address:port of your server
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Credentials', true);
next();
});
//enable pre-flight
app.options('*', cors());
But before copy and pasting, just so you know that you need to npm install cors --save
before importing the cors. The above sample code simply means:
axios.create({
withCredentials: true
});
to say: both react and express are agree to use CORS. And likewise in the other http libraries. Here is some documentation you can have a look at: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Upvotes: 3
Reputation: 3317
Here's my sample use of CORS with expressJs, this is needed to be done on backend or server-side. Server stops access of it's API from outside world not client-side.
// IP's allowed all access this server
let whitelist = ['http://localhost:3000', 'http://127.0.0.1:3000'];
let corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
};
// Cross-Origin Resource Sharing
app.use(cors(corsOptions));
Upvotes: 0
Reputation: 217
Instead of using AJAX to request the endpoint, I should have navigated there through the browser. I used an <a>
tag with an href
of "http://localhost:4000" and it worked as expected.
Upvotes: 2