Webpack开发服务器中Twitter api调用的CORS问题 [英] CORS issue with Twitter api calls in Webpack dev server

查看:182
本文介绍了Webpack开发服务器中Twitter api调用的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,即从Twitter api(使用npm软件包Twitter)获取响应。在Chrome中,我得到:

I'm running into an issue getting responses from the twitter api (using npm package Twitter). In Chrome I am getting:


无法加载 https://api.twitter.com/1.1/search/tweets.json?q=node.js :对预检请求的响应没有无法通过访问控制检查:所请求的资源上没有 Access-Control-Allow-Origin标头。因此,不允许访问来源‘ http:// localhost:3000 。响应的HTTP状态代码为400。如果不透明的响应满足您的需求,请将请求的模式设置为 no-cors,以在禁用CORS的情况下获取资源。

Failed to load https://api.twitter.com/1.1/search/tweets.json?q=node.js: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

因此我启用了带有插件的CORS,错误更改为:

So I enable CORS with a plugin and the error changes to:


无法加载 https://api.twitter.com/1.1/search/tweets.json?q = node.js :飞行前响应具有无效的HTTP状态代码400。

Failed to load https://api.twitter.com/1.1/search/tweets.json?q=node.js: Response for preflight has invalid HTTP status code 400.

我不确定该怎么做这一点。我在webpack.config.js中尝试了几种不同的方法:

I'm not sure what to do at this point. I have tried a couple different things in my webpack.config.js:

var path = require('path');
var webpack = require('webpack');
var Dotenv = require('dotenv-webpack');

module.exports = {
    devServer: {
        inline: true,
        historyApiFallback: true,
        contentBase: './src',
        port: 3000,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
        },
        proxy: {
            "/api": "http://localhost:3000"
        }
    },
    devtool: 'cheap-module-eval-source-map',
    entry: './dev/js/index.js',
    module: {
        loaders: [
            {
                test: /\.js$/,
                loaders: ['babel'],
                exclude: /node_modules/
            },
            {
                test: /\.scss/,
                loader: 'style-loader!css-loader!sass-loader'
            },
            {
                loader: 'json-loader',
                test: /\.json$/ 
            }
        ]
    },
    output: {
        path: 'src',
        filename: 'js/bundle.min.js'
    },
    node: {
        console: false,
        fs: 'empty',
        net: 'empty',
        tls: 'empty'
    },
    plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
        new Dotenv({
            path: './.env',
            safe: false
        })
    ]
};

这是我要拨打的电话

import Twitter from 'twitter';

const client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  bearer_token: process.env.TWITTER_BEARER_TOKEN
});

client.get('search/tweets', {q: 'node.js'}, function(error, tweets, response) {
   console.log(tweets);
});

我也在启用了CORS插件的情况下也在firefox中尝试过,但出现此错误:

I tried it in firefox as well with a CORS plugin enabled and I get this error:


跨域请求被阻止:同源策略禁止读取 https://api.twitter.com/1.1/search/tweets.json?q=node.js 。 (原因:CORS预检频道未成功。)

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.twitter.com/1.1/search/tweets.json?q=node.js. (Reason: CORS preflight channel did not succeed).


推荐答案

您的浏览器设置了原始标头向Webpack开发服务器代理发出HTTP请求时,代理会将此原始标头转发到Twitter。 Twitter很可能会基于其非法来源拒绝该请求。您可以通过在转发请求之前删除原始标头来解决此问题:

Your browser sets an origin header when making the HTTP request to your webpack dev server proxy and the proxy forwards this origin header to Twitter. Most likely Twitter will reject the request based on its illegal origin. You can get around this by removing the origin header before the request is forwarded:

devServer: {
  ...,
  proxy: {
    ...,
    onProxyReq: function onProxyReq(proxyReq, req, res) {
      proxyReq.removeHeader("origin")
    }
  }
}

这篇关于Webpack开发服务器中Twitter api调用的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆