2017-01-23 27 views
0

這是我的第一個React.js應用程序,我試圖做一個簡單的API調用非auth api。我在Heroku(Framework: React.js (create-react-app))及其運行的Express Node.js中部署應用程序並使用React路由器。 我的問題是,在一個簡單的按鈕點擊(調用handleClick())我想打一個API GET請求,但我通過控制檯不斷收到錯誤消息Express Node.js + React路由器無法進行API調用? 「訪問控制起源」

提取API無法加載 https://rest-it-test.herokuapp.com/rest。否 「訪問控制 - 允許來源」標題出現在請求的 資源中。原產地'https://myherokuapp.herokuapp.com'是 因此不允許訪問。響應的HTTP狀態碼爲400. 如果一個不透明的響應符合您的需求,請將請求的模式設置爲 'no-cors'以取消禁用CORS的資源。

的src /組件/應用

import React, { PropTypes, Component } from 'react'; 
import classnames from 'classnames'; 

import logo from './logo.svg'; 
import './style.css'; 

var Twitter = require('twitter'); 
var request = require('request'); 

var client = new Twitter({ 
    consumer_key: process.env.TWITTER_CONSUMER, 
    consumer_secret: process.env.TWITTER_SECRET 
}); 



class App extends Component { 
    // static propTypes = {} 
    // static defaultProps = {} 
    // state = {} 
    constructor(props) 
    { 
    super(props) 
    this.state = { 
     input: "" 
    } 
    this.handleChange = this.handleChange.bind(this); 
    this.handleClick = this.handleClick.bind(this); 
    } 

    getInitialState(){ 
    return { input: '' }; 
    } 

    handleChange(e) { 
    this.setState({ input: e.target.value }); 
    } 

    handleClick(){ 
    console.log(this.state.input); 
    request('https://rest-it-test.herokuapp.com/rest', function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
      console.log(body) // Print the google web page. 
     } 
    }); 

    } 

    render() { 
    const { className, ...props } = this.props; 
    return (
     <div className={classnames('App', className)} {...props}> 
     <div className="App-header"> 
      <img src={logo} className="App-logo" alt="logo" /> 
      <h2>Welcome to React</h2> 
     </div> 
     <p className="App-intro"> 
      <code>src/App.js</code> and save to reload. 
     </p> 
     <p> 
      Testing HTML!!! 
     </p> 
     <input type="text" onChange={ this.handleChange } /> 
     <input 
      type="button" 
      value="Search" 
      onClick={this.handleClick} 
     /> 
     </div> 
    ); 
    } 
} 

export default App; 

服務器/ app.js

const express = require('express'); 
const morgan = require('morgan'); 
const path = require('path'); 
var cors = require('cors'); 

const app = express(); 

app.use(cors()); 

// Setup logger 
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms')); 

// Serve static assets 
app.use(express.static(path.resolve(__dirname, '..', 'build'))); 

// Use for React Router... Will always return main. 
app.get('*', (req, res) => { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    res.header("Access-Control-Allow-Headers", "Content-Type"); 
    res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS"); 
    res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html')); 
}); 


module.exports = app; 

這裏是解決方案的列表我曾嘗試:

  1. 使用不同的庫,例如作爲restler。
  2. 在請求調用中嘗試了傳遞標頭Access-Control-Allow-Origin「,」*「,Access-Control-Allow-Headers」,「Origin,X-Requested-With,Content-Type,Accept」等。本身。

有沒有其他的解決方案,我能想到的,如果有人已經解決了這個請讓我知道。

謝謝!

+0

我不認爲它是你的錯。看看: http://stackoverflow.com/questions/35879943/twitter-api-authorization-fails-cors-preflight-in-browser –

+0

謝謝,但它不是Twitter。它的任何API GET請求都會給我帶來錯誤。 –

回答

0

您遇到了幾個不同的問題。

首先,CORS。除非客戶端請求和遠程服務器響應都包含解決此問題所需的標頭,否則瀏覽器實質上就是與域相關的沙盒。您引用的錯誤消息告訴您響應已被阻止,因爲響應中不包含任何「Access-Control-Allow-Origin」標頭。這不是您可以通過在Express服務器上設置標題來解決的問題;這是Twitter的API必須設置的東西。據我所知,Twitter不允許這樣做,所以它是一個死路一條。

其次,檢查出狀態碼。如果你能得到過去CORS問題,您會收到他們的迴應是這樣的:

{ 
 
    "errors": [ 
 
    { 
 
     "code": 215, 
 
     "message": "Bad Authentication data." 
 
    } 
 
    ] 
 
}

爲了訪問API,你將不得不從你的服務器讓您的要求(這將不會有CORS問題),並可能通過oauth流進行身份驗證。

+0

感謝您的回答,但請看我列表中的#2。我從我知道的作品中嘗試了一次寧靜的GET,並且它不需要認證。不要緊,如果它是嘰嘰喳喳我正在從GET,它只是做任何簡單的GET請求失敗。 –

+0

沒有看到這個請求,我不能做太多的事情,但我可以推薦在郵遞員中嘗試它,並仔細檢查響應。 –