2017-01-08 120 views
0

我正在嘗試使用superagent發出post請求,但它總是失敗。我已經嘗試了很多來自互聯網的解決方案,包括添加多個頭文件,但似乎都沒有工作。代碼:React中的superagent發送請求失敗

createUser() { 
var email = this.refs.email.value; 
Request.post('http://advacedcrm.local/api/users/create').set('Accept', 'application/json').send({email: email}).then((response) => { 
    console.log(response); 
}); 

}

我不得不提的是,API也是我做的,我把一些標題有:

header('Access-Control-Allow-Origin: http://localhost:3000'); 

routes.php文件的開始(在Laravel 5.2)。 的API中間件:

public function handle($request, Closure $next) 
{ 
    if ($request->isMethod('options')) { 
     return response('', 200) 
      ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE') 
      ->header('Access-Control-Allow-Headers', 'accept, content-type, x-xsrf-token, x-csrf-token'); 
    } 

    return $next($request); 
} 

但是,當我將它張貼,錯誤我收到:

XMLHttpRequest cannot load http://advacedcrm.local/api/users/create. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. 

所以我的想法,有什麼不好?

回答

2

可以安裝的SuperAgent

npm install superagent --save 

然後做專呼叫服務器

import request from "../../node_modules/superagent/superagent"; 

request 
.post('http://localhost/userLogin') 
.set('Content-Type', 'application/x-www-form-urlencoded') 
.send({ username: "username", password: "password" }) 
.end(function(err, res){ 
console.log(res.text); 
}); 
相關問題