React / Node / Express和Google OAuth的CORS / CORB问题 [英] CORS/CORB issue with React/Node/Express and google OAuth
问题描述
我有一个React应用,试图将OAuth添加到Node / Express / MySQL后端。我的React应用程序托管在localhost:3000上,而快速服务器托管在localhost:4000上。我在反应应用程序的package.json文件中添加了代理: http:// localhost:4000 以发送请求到服务器。 OAuth的授权JavaScript来源为 http:// localhost:4000 。授权的重定向URI为 http:// localhost:4000 / auth / google / redirect 。
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:
有人说所请求的资源上没有'Access-Control-Allow-Origin'标头。
One says No 'Access-Control-Allow-Origin' header is present on the requested resource.
另一个人说:跨域读取阻止(CORB)阻止了跨域响应.... MIME类型为text / html。
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.
这是我的react app的package.json文件中的代码:
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));
}
这是服务器中的代码
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!"));
推荐答案
这是您需要的新中间件的示例代码要安装以表示之前,您可以定义以下任何路线:
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());
但是在复制和粘贴之前,只是要知道您需要 npm在导入cors之前,先安装cors --save
。上面的示例代码仅表示:
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:
- 我们允许使用不同的IP地址访问您定义的所有路由的服务器
- 在标头中允许使用 X-Requested-With和 Content-Type参数。通常,您不必特别定义它们,但是拥有它们是件好事。
- 只有在将allow凭据设置为true的情况下,您的会话/ cookie才能在前端刷新页面期间存储,我认为这可能对您的未来发展有所帮助。
- 飞行前请求也将被允许,默认情况下,许多Http库都会发送该请求。
- 对于前端,如果您使用的是axios,则确实需要:
axios.create({
表示:无论是回应还是表达都同意使用CORS。在其他http库中也是如此。
withCredentials:true
} );
- we allow a different ip address to access the server for all the routes you defined
- Allow a 'X-Requested-With' and a 'Content-Type' parameters inside the header. You normally don't have to specifically define these but its good to have them.
- Only with the allow credentials set to true your session/cookies are able to store during front-end refreshing the pages, which I think might be helpful for your future development.
- pre-flight request will also be allowed, which many Http libraries will send by default.
- for your front-end, if you are using axios, you do need:
axios.create({ withCredentials: true });
to say: both react and express are agree to use CORS. And likewise in the other http libraries.
以下是一些文档,您可以查看:
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
https://developer.mozilla.org/en-US/docs/Web/HTTP / CORS
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
这篇关于React / Node / Express和Google OAuth的CORS / CORB问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!