Axios发布请求被CORS政策Vue.js禁止

时间:2019-05-15 09:00:42

标签: php http vue.js cors axios

我的网站上有一个表格,如果用户输入用户名和密码,则可以请求apikey。目前,我正在通过发布请求将Axios的用户名和密码发送到api。但是,它一直给我这些错误:

OPTIONS http://localhost/Leerjaar%203/api/apikey/ 500 (Internal Server Error)
Access to XMLHttpRequest at 'http://localhost/Leerjaar%203/api/apikey/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我正在使用Vue.js开发此网站,并且api是使用PHP制作的(我自己没有开发api)。每当我在Postman上发送带有相应数据的邮寄请求时,它都可以正常运行,但是当我在Axios上尝试时,它将无法正常工作。

我已经尝试在我的api和我的发布请求中设置标头,但是我似乎找不到问题。我读了一些有关期权要求的内容,但我不知道该怎么做。我希望有人可以帮助我解决我的问题。

发送发布请求的方法:

formSubmit(e) {
            e.preventDefault();
            let currentObj = this;
            axios.post('http://localhost/Leerjaar%203/api/apikey/', {
                docent: this.docentNaam,
                wachtwoord: this.wachtwoord,
                headers: {
                    "Content-type": "application/json;charset=UTF-8",
                    "Access-Control-Allow-Origin": "*",
                    "baseURL": "http://localhost:8080",
                    "timeout": 10000,
                    "withCredentials": "true"
                },
                validateStatus: (status) => {
                    return true;
                }
            })
            .then(function (response) {
                currentObj.output = response.data;
                console.log(response.data);
            })
            .catch(function (error) {
                console.log(error);
            }); 
        }

我的表单:

<form @submit="formSubmit">
  <div class="form-group">
    <label for="docentNaam">Naam:</label>
    <input v-model="docentNaam" type="text" class="form-control" placeholder="Docenten afkorting">

    <label for="wachtwoord">Wachtwoord</label>    
    <input v-model="wachtwoord" type="password" class="form-control" placeholder="Wachtwoord">

    <button type="submit" class="btn btn-primary">Submit</button>
  </div>
</form>

api文件:

<?php    
session_start();

include "../errors.inc.php";
include "../credentials.inc.php";
include "../database.inc.php";

$docent = Docent();

if (!isset($_POST["wachtwoord"]))    fout(400, "wachtwoord ontbreekt");
if ($_POST["wachtwoord"] !== "test") fout(401, "wachtwoord incorrect");

header('Access-Control-Allow-Origin: *');     
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
header('content-type: application/json; charset=utf-8');
echo '{"apikey":"'.md5(md5($docent)).'"}';  

这是我发送帖子请求时的标头:

https://imgur.com/a/A1hpqVJ

0 个答案:

没有答案