我正在尝试在客户的网站上显示我的小部件。但是我无法在Laravel 5.5中使用CORS。这是我的代码:
public / js / cb.js 客户网站上加载的JavaScript文件。
window.onload = do_request();
function do_request()
{
var url = "http://cb.dev.server-website.com/api/books/";
var book_id = 0;
var elementExists = document.getElementById("cb_script");
if (typeof elementExists != "undefined" && elementExists) {
var book_id = elementExists.getAttribute('data-id');
}
if (typeof book_id != "undefined" && book_id) {
var parts = book_id.split('_');
var loc = parts.pop();
url += loc;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
xmlhttp.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With, accept, content-type");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsondata = JSON.parse(xmlhttp.responseText);
if (
typeof(jsondata) != "undefined" && jsondata != ""
&& typeof(jsondata['data']) != "undefined" && jsondata['data']
) {
document.getElementById("stirbook_live").innerHTML = jsondata['data'].html;
do_modal('myModal');
}
}
};
xmlhttp.send();
}
routes / api.php Laravel API路线文件
Route::resource('books', 'Api\BooksapiController')
->middleware('preflight');
app / Http / Middleware / PreflightResponse.php Laravel Middleware文件
namespace App\Http\Middleware;
use Closure;
class PreflightResponse
{
public function handle($request, Closure $next)
{
if ($request->getMethod() === "OPTIONS") {
return response('');
}
return $next($request);
}
}
app / Http / Controllers / ApiBooksapiController.php Laravel控制器文件
public function show($id)
{
$data = $book_array = array();
$output = '';
$book = DB::table('books')
->join('questions', 'books.id', '=', 'questions.book_id')
->select('books.user_id', 'books.website', 'questions.id AS question_id', 'questions.question')
->get()->toArray();
if (is_array($book) && count($book)) {
$questions_html = '';
for ($i = 0; $i < count($book); $i++) {
$questions_html .= '<h5>Q: ' . $book[$i]->question . '</h5>';
$answers = DB::table('answers')
->where([
['question_id', $book[$i]->question_id],
['status', 1]
])
->select('answers.id', 'answers.answer', 'answers.o_quantity', 'answers.o_percentage', 'answers.o_schedule', 'answers.o_overunder', 'answers.o_overunder')
->get()->toArray();
if (is_array($answers) && count($answers)) {
$questions_html .= '<ul style="list-style-type: disc;">';
for ($j = 0; $j < count($answers); $j++) {
$questions_html .= '<ol>
<input type="radio" name="question_' . $book[$i]->question_id . '" value="1" id="answer_' . $j . '_' . $book[$i]->question_id . '" class="radio-class" onclick="do_survey(' . $book[$i]->question_id . ', ' . $answers[$j]->id . ', ' . $answers[$j]->o_quantity . ')" />
<label for="answer_' . $j . '_' . $book[$i]->question_id . '">' . $answers[$j]->answer . '</label>
<input type="hidden" name="offer_' . $j . '_' . $book[$i]->question_id . '" value="' . $answers[$j]->o_quantity . '" />
</ol>';
}
$questions_html .= '</ul>';
}
}
$output .= '
<!-- Trigger/Open The Modal -->
<button id="myBtn" class="btn btn-primary">Opt-out</button>
<!-- The Modal -->
<div id="myModal" class="modal" style="display: none; position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4);">
<!-- Modal content -->
<div class="modal-content" style="background-color: #fefefe; margin: auto; padding: 20px; border: 1px solid #888; width: 80%;">
<span class="close" style="color: #aaaaaa; float: right; font-size: 28px; font-weight: bold;">×</span>
<div id="book_form">
<h3>book</h3>
<form name="fbook" action="#" method="post">
' . $questions_html . '
</form>
</div>
<div id="offer_resp" style="display: none;">
<h3>Wait!!!</h3>
<div id="rm_body">
<p>Please don\'t go! How\'s this, we\'ll give you <span class="number-of-months"><numberofmonths></span> free month(s) for trying us out a little longer.</p>
</div>
<button id="yes_button" class="btn btn-primary" onclick="yes_response()" value="">Yes, give me <span class="number-of-months"><numberofmonths></span> month(s) free!</button>
<button id="no_button" class="btn btn-default" onclick="no_response()" value="">No thank you, I wish to cancel now!</button>
</div>
</div>
</div>
';
}
if (isset($output) && $output) {
$data['html'] = $output;
}
return response()->json(['data' => $data], 200);
}
但它不起作用。当我在Postman中尝试它时它工作正常。但是,当我在任何其他网站上尝试它时,它会将请求从GET更改为OPTIONS并且不提供任何内容。这可能是因为我的服务网站属于子域名吗?我花了一整天时间搞清楚这个解决方案,我已经应用了几乎所有可用的解决方案。
答案 0 :(得分:0)
OPTIONS
调用是由某些浏览器自行发出的飞行前请求,用于检查所请求的URL上可接受的请求类型(GET,POST,PUT ...)。
Chrome在尝试CORS请求时首先发送OPTIONS请求。
答案 1 :(得分:0)
好的,所以我找到了问题的解决方案。真正的问题出在我用GET Request发送的标题中。事实证明,当发送GET请求时,不需要 public / js / cb.js 中提到的标题。只需发送简单的GET请求即可。
以下是修改后的 public / js / cb.js 文件代码:
window.onload = do_request();
function do_request()
{
var url = "http://cb.dev.server-website.com/api/books/";
var book_id = 0;
var elementExists = document.getElementById("cb_script");
if (typeof elementExists != "undefined" && elementExists) {
var book_id = elementExists.getAttribute('data-id');
}
if (typeof book_id != "undefined" && book_id) {
var parts = book_id.split('_');
var loc = parts.pop();
url += loc;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsondata = JSON.parse(xmlhttp.responseText);
if (
typeof(jsondata) != "undefined" && jsondata != ""
&& typeof(jsondata['data']) != "undefined" && jsondata['data']
) {
document.getElementById("stirbook_live").innerHTML = jsondata['data'].html;
do_modal('myModal');
}
}
};
xmlhttp.send();
}
routes / api.php 文件无需更改,但 app / Http / Middleware / PreflightResponse.php 文件需要进行少量更改。
app / Http / Middleware / PreflightResponse.php 文件的修改代码:
namespace App\Http\Middleware;
use Closure;
class PreflightResponse
{
public function handle($request, Closure $next)
{
if ($request->getMethod() === "OPTIONS") {
return response('')
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
现在都在这里设置。 PreflightResponse 中间件将发送响应标头...
Access-Control-Allow-Origin: *
到客户的网站。告诉它服务器接受每个API请求的CORS请求。