即使上传到Heroku,Spotify仍会继续返回CORS政策

时间:2019-05-23 13:50:24

标签: api cors spotify mern

我正在尝试使用Spotify API获取信息,但一直返回CORS政策。我有一个React前端和一个Express后端。我这样做了,以便当React正面单击按钮时,它会重定向到授权页面(我使用的是护照JS)。但是,它没有返回此页面,而是返回以下内容:

从原点“ https://accounts.spotify.com/authorize?response_type=code&redirect_uri=http%3A%2F%2Ftestconapi.herokuapp.com%2Fauth%2Fspotify%2Fcallback&scope=user-read-email%20user-read-private&client_id=76fb50b11f85463ba0ce33609879aab5”到“ https://testconapi.herokuapp.com/spotify”(从“ https://testconapi.herokuapp.com”重定向)的访问已被阻止

我尝试在LocalHost中执行此操作,但我读到它可能是因为我的后部和前部在不同的服务器上运行,因此,我尝试对其进行修复,但从未成功。我想,也许如果我将其上传到heroku中,它们全都在同一台服务器上,但是它也不起作用。也许我做错了。

正在从后端发出请求。

我尝试使用npm cors,也尝试上传到Heroku。还从其他网站复制并粘贴了很多代码,试图解决该问题,但均无济于事。

这是我的app.js(删除了不必要的代码,请粘贴到这里):

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const keys = require('./config/keys');
const passportSetup = require('./config/passport-setup');
const cors = require('cors');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
let getInfoRouter = require('./routes/v1/getInfo');
let getUserListenedSongs = require('./routes/v1/getListenedSongsDB');
let getUsers = require('./routes/v1/getUsers');
const passport = require('passport');

var app = express();

// Setting up the cors config
app.use(cors());

// ... other app.use middleware
app.use(express.static(path.join(__dirname, 'client', 'build')));

// ...
// Right before your app.listen(), add this:
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});

app.use((req, res, next) => {
  res.append('Access-Control-Allow-Origin', ['*']);
  res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.append('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(
  '/spotify',
  passport.authenticate('spotify', {
    scope: ['user-read-email', 'user-read-private']
  }),
  function(req, res) {
    console.log('Termine aqui!');
    res.send(true);
  }
);

app.use(
  '/auth/spotify/callback',
  passport.authenticate('spotify'),
  (req, res) => {
    console.log('this is the callback function');
    res.send(true);
  }
);



这是来自客户端的包json:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^3.9.3",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-router": "^5.0.0",
    "react-router-dom": "^5.0.0",
    "react-scripts": "3.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8000"
}

这是react app.js,组件非常基础,路径很重要:


function App() {
  return (
    <Router>
      <div className="App">
        <Nav />
        <Switch>
          <Route path="/listened-songs" component={Listened} />
          <Route path="/auth/spotify/callback" component={Logged} />
          <Route path="/connections/:id?" component={Connection} />
          <Route path="/" component={Home} />
        </Switch>
      </div>
    </Router>
  );
}


这是护照js设置:

const passport = require('passport');
const SpotifyStrategy = require('passport-spotify').Strategy;
const keys = require('./keys');

passport.use(
  new SpotifyStrategy(
    {
      clientID: keys.spotify.clientID,
      clientSecret: keys.spotify.clientSecret,
      callbackURL: '/auth/spotify/callback'
    },
    function(accessToken, refreshToken, expires_in, profile, done) {
      console.log(profile);
      // User.findOrCreate({ spotifyId: profile.id }, function(err, user) {
      //   return done(err, user);
      // });
    }
  )
);

感谢您的帮助,因为我一直在这个问题上呆了一周。如果您需要任何其他代码,或者希望我上传我的代码并通过github共享,请询问。

编辑:否则,如果我做错了很多事情,如果您可以告诉我如何以正确的方式做事,我也将不胜感激。我的目标只是能够在没有此CORS问题的情况下从React进行身份验证。或者,如果我应该采用其他方式。

0 个答案:

没有答案