【问题标题】:CORS redirection problem with Spotify API?Spotify API 的 CORS 重定向问题?
【发布时间】:2021-08-11 11:53:40
【问题描述】:

我的 Web 应用程序在前端使用 Angular 12,在后端使用带有 Express.js 的 Node.js 12.16.0。我正在尝试开发一个 Web 应用程序,允许用户使用他们的 Spotify API 登录,但即使在查找了一堆帖子之后,我在使用 CORS 时也遇到了很多麻烦。在前端,我的代码只是使用 HttpClient 调用我的 /login 端点。

public login(): Observable<any> {
    const url = backendURL + BackendEndpoints.Login;

    return this.http.get<any>(url, {withCredentials: true});
}

从后端来看,我的端点设置如下所示,其中填充了适当的变量,应该将我的前端网页重定向到 Spotify 登录页面。

router.get("/login", (req, res) => {
    var state = generateRandomString(16);

    var scope = 'user-read-email playlist-read-private'
    res.redirect('https://accounts.spotify.com/authorize?' +
        querystring.stringify({
            response_type: 'code',
            client_id: CLIENT_ID,
            scope: scope,
            redirect_uri: REDIRECT_URI,
            state: state,
            show_dialog: true
        }));
});

我也在中间件中使用了 cors 包。

this.expressApp.use(cors({origin: 'http://localhost:4200', credentials: true}));

我的前端没有重定向,而是收到此 CORS 错误。

跨域资源共享策略拒绝跨域重定向到 https://accounts.spotify.com/login?continue=https%3A%2F%2Faccounts.spotify.com%2Fauthorize%3Fscope%3Duser-read-email%2Bplaylist-read-private%26response_type%3Dcode%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A4200%252Fjoin%26state%3DjOZBRfRFxNi3auk6%26client_id%3D7e37838f2aa3449da5ee2b592a1a185e%26show_dialog%3Dtrue:Access-Control-Allow-Origin 不允许 Origin null。

为什么我仍然收到 CORS 错误?如果可能的话,我想只配置我的后端而不是制作代理服务器。

【问题讨论】:

    标签: node.js angular express cors spotify


    【解决方案1】:

    编辑:不工作

    您是否尝试在 Angular 调用的标题中添加 Origin ? 类似的东西:

    public login(): Observable<any> {
        const url = backendURL + BackendEndpoints.Login;
        const header = new HttpHeaders();
        header.append('Origin', 'http://localhost:4200');
    
        return this.http.get<any>(url, {withCredentials: true, headers: header});
    }
    

    编辑2:

    您可以尝试创建链接:

     <a href="/login" #spotifyConnectLink></a>
    

    然后你创建一个按钮来要求用户点击连接:

     <button (click)='handleCacheAndLaunchConnection()'>Connect To Spotify</button>
    

    在您的 ts 上,您创建了 handleCacheAndLaunchConnection 函数,然后强制单击带有 Viewchild 的链接:

     @ViewChild('spotifyConnectLink') spotifyConnectLink: ElementRef;
    
     handleCacheAndLaunchConnection() {
         //Do the stuff you need for app and cache
    
        let el: HTMLElement = this.spotifyConnectLink.nativeElement;
        el.click();
     }
    

    希望这项工作

    【讨论】:

    • 刚试过。现在我收到了另一个错误:“[Spotify API Link] 被跨域资源共享策略拒绝:Access-Control-Allow-Origin 不允许 Origin localhost:4200
    • 我发现了一些可能对你有帮助的东西:stackoverflow.com/questions/26029627/…他们说要使用这样的&lt;a href="/auth/facebook"&gt;&lt;/a&gt;
    • 以你为例,你可以尝试这样做:
    • 这可行,但我更愿意在前端调用一个函数,因为我想在我的应用程序和缓存中生成一些东西。
    • 非常聪明!谢谢!
    猜你喜欢
    • 2015-01-10
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多