node.js - React/Node/Express 和 google OAuth 的 CORS/CORB 问题

标签 node.js reactjs express cors passport.js

我有一个 React 应用程序,我正在尝试使用 OAuth 添加 Node/Express/MySQL 后端。我的 React 应用托管在 localhost:3000 上,而 express 服务器位于 localhost:4000 上。我在 React 应用程序的 package.json 文件中添加了“代理”:“http://localhost:4000”以向服务器发送请求。 OAuth 的授权 Javascript 来源是 http://localhost:4000 .授权重定向 URI 是 http://localhost:4000/auth/google/redirect .

这些是我在尝试访问服务器上的路由时在浏览器控制台中遇到的错误:

有人说请求的资源上不存在“Access-Control-Allow-Origin” header 。

另一个说“跨源读取阻止 (CORB) 阻止了跨源响应....使用 MIME 类型文本/html。”

我不知道我做错了什么,从昨天开始我就一直卡住了。

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 应用程序的 package.json 文件中的代码:

{
  "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"
}

这是我的 React 应用程序中将请求发送到服务器的代码:

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

最佳答案

这是您需要安装的新中间件的示例代码,以表达之前您定义任何路由:

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

但在复制和粘贴之前,只是让您知道在导入 cors 之前需要 npm install cors --save。上面的示例代码简单的意思是:

  1. 我们允许不同的 ip 地址访问您定义的所有路由的服务器
  2. 在 header 中允许使用“X-Requested-With”和“Content-Type”参数。您通常不必专门定义这些,但拥有它们是件好事。
  3. 只有将 allow credentials 设置为 true,您的 session /cookie 才能在前端刷新页面期间存储,我认为这可能对您 future 的开发有所帮助。
  4. 飞行前请求也将被允许,许多 Http 库将默认发送该请求。
  5. 对于您的前端,如果您使用的是 axios,则需要:axios.create({ withCredentials:真 }); 表示:react 和 express 都同意使用 CORS。同样在其他 http 库中。

以下是您可以查看的一些文档: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

关于node.js - React/Node/Express 和 google OAuth 的 CORS/CORB 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52728346/

相关文章:

javascript - Socket.io 聊天服务器不提供 SSL 证书

node.js - 为什么在 console.developers.google.com 中创建 API key 时收到此错误消息 :'This API project was not found'

arrays - Mongodb $pull 与 async/await 无法正常工作

reactjs - 如何检测 React Material UI 选择字段是否展开?

javascript - 如何在 reactjs ES6 的 JSONArray 上使用 .map() 函数

javascript - express 和 Passport 错误 : Unknown authentication strategy "login"

regex - Node js Express 框架 - 正则表达式不起作用

javascript - 在 node.js 中向 multer 添加逻辑/验证(express)

node.js - Node.js 有 virtualenv 吗?

javascript - 确保函数仅在 componentDidMount 或 componentDidUpdate 中被调用一次