我在从 twitter api 获取响应时遇到问题(使用 npm 包 Twitter)。在 Chrome 中我得到:
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,错误更改为:
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 中尝试了几种不同的方法:
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);
});
我在 Firefox 中尝试了它并启用了 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).
最佳答案
我只能想到一个解决方法:
- 使用 Chrome 扩展 Allow-Control-Allow-Origin
- 使用代理:不要访问
https://api.twitter.com/1.1/search/tweets.json?q=node.js
,而是使用https:/等代理/cors-anywhere.herokuapp.com/
作为前缀:https://cors-anywhere.herokuapp.com/https://api.twitter.com/1.1/search/tweets.json? q=node.js
关于node.js - Webpack 开发服务器中 Twitter api 调用的 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49001011/