简体   繁体   English

Express.js - 跨域请求被阻止

[英]Express.js - Cross-Origin Request Blocked

I have a Node.js server running on localhost port 3000 .我有一个 Node.js 服务器在 localhost 端口3000上运行。 I also have a Vue.js application running on port 8080 .我还有一个 Vue.js 应用程序在端口8080上运行。 I've implemented passportjs (Google strategy) on my login form that is written in Vue.js.我已经在我用 Vue.js 编写的登录表单上实施了passportjs(谷歌策略)。

However, when I click on the Google+ button, I have a CORS blocked error which tells me that I have a missing CORS even though I have enabled cors in my server code.但是,当我单击 Google+ 按钮时,出现 CORS 阻止错误,它告诉我即使我在服务器代码中启用了 cors,我也缺少 CORS。

I've tried changing parameters to cors() :我试过将参数更改为cors()

app.use(cors({origin: 'http://localhost:3000', credentials: true}));

I've also tried adding Header set Access-Control-Allow-Origin '*' to my apache2.conf file.我还尝试将Header set Access-Control-Allow-Origin '*'到我的apache2.conf文件中。

I also get a HTTP 302 code every time I hit the button.每次按下按钮时,我都会收到一个 HTTP 302代码。

Node.js file: Node.js 文件:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');

const app = express();

app.use(cors());

// Routes
app.use('/user', users);

// Passport strategy
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: '/user/google/redirect'
},
function(accessToken, refreshToken, profile, done) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
        return done(err, user);
    });
}));

// Server start
app.listen(3000, (req, res) => {
    console.log(`Listening to port 3000...\n`);
});

Router:路由器:

// auth with google+
router.get('/google', passport.authenticate('google', 
    { scope: ['https://www.googleapis.com/auth/plus.login']  }
));

// callback route for google to redirect to
router.get('/google/redirect', passport.authenticate('google', 
    { failureRedirect: '/login' }),
    function(req, res) {
    res.send('Done!');
});

Vue.js file: Vue.js 文件:

<template>
    <v-card class="elevation-12" v-on:submit.prevent="login">
        <mdb-btn align-center justify-center class="btn-gplus" icon="google-plus-g" fab v-on:click="authGoogle()">Google +</mdb-btn>
    </v-card>
</template>

<script>
import axios from 'axios';
import router from '../router/router';
import { mdbBtn } from 'mdbvue';

const { URL } = require('../config');

export default {
  name: 'Login',
  methods: {
    authGoogle () {
      axios.get(`${URL}/user/google`, {
      }).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err);
      })
    }
  },
  components: {
    mdbBtn
  }
};
</script>

When I enter http://localhost:3000/user/google/ in my browser, the Google login page opens successfully but I cannot accomplish this in my code.当我在浏览器中输入http://localhost:3000/user/google/时,Google 登录页面成功打开,但我无法在我的代码中完成此操作。

The cross-origin request blocked error is not caused by the your server configuration but by Google's server configuration.跨域请求被阻止的错误不是由您的服务器配置引起的,而是由 Google 的服务器配置引起的。 Your server tries to redirect the client to Google's login page.您的服务器尝试将客户端重定向到 Google 的登录页面。 For security reasons, browsers do not always allow these kinds of cross origin redirects (otherwise you could always get around CSRF protection by adding a redirecting endpoint page on your own domain).出于安全原因,浏览器并不总是允许这些类型的跨源重定向(否则您总是可以通过在您自己的域中添加重定向端点页面来绕过 CSRF 保护)。 To fix the problem, you can use an actual html link to http://localhost:3000/user/google/ , like so:要解决此问题,您可以使用指向http://localhost:3000/user/google/的实际 html 链接,如下所示:

<a href="http://localhost:3000/user/google/">Google+</a>`

You can add cors headers through response headers in middleware:您可以通过中间件中的响应头添加 cors 头:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    next();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM