简体   繁体   English

本地主机已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态

[英]Localhost has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

So I am working on my first Vue project and I came across a problem that I can't seem to solve.所以我正在做我的第一个 Vue 项目,但遇到了一个我似乎无法解决的问题。

I am trying to perform CRUD operations with Vue and my backend RESTful API service, but I keep getting this error:我正在尝试使用 Vue 和我的后端 RESTful API 服务执行 CRUD 操作,但我不断收到此错误:

Access to XMLHttpRequest at 'http://localhost:8080/parties/3' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

When i was searching for the answer I came across this:当我在寻找答案时,我遇到了这个:

header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")

And I believe this is in the right direction of the answer, but I don't really know where to put in my code (I think it probably will have to go into the script of the Vue page, but I am not really sure)而且我相信这是正确的答案方向,但我真的不知道在哪里输入我的代码(我认为它可能必须将 go 放入 Vue 页面的脚本中,但我不太确定)

This is my Vue page:这是我的 Vue 页面:

<template>
  <div v-if="currentParty" class="edit-form">
    <h4>Party</h4>
    <form>
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name"
               v-model="currentParty.name"
        />
      </div>
      <div class="form-group">
        <label for="description">Description</label>
        <input type="text" class="form-control" id="description"
               v-model="currentParty.description"
        />
      </div>

      <div class="form-group">
        <label><strong>Status:</strong></label>
        {{ currentParty.isPartyNational ? "isPartyNational" : "Pending" }}
      </div>
    </form>

    <button class="badge badge-primary mr-2"
            v-if="currentParty.isPartyNational"
            @click="updatePublished(false)"
    >
      UnPublish
    </button>
    <button v-else class="badge badge-primary mr-2"
            @click="updatePublished(true)"
    >
      Publish
    </button>

    <button class="badge badge-danger mr-2"
            @click="deleteParty"
    >
      Delete
    </button>

    <button type="submit" class="badge badge-success"
            @click="updateParty"
    >
      Update
    </button>
    <p>{{ message }}</p>
  </div>

  <div v-else>
    <br />
    <p>Please click on a Party...</p>
  </div>
</template>

<script>
import PartyDataService from "@/services/PartyDataService";

export default {
  name: "Party",
  data() {
    return {
      currentParty: null,
      message: ''
    };
  },
  methods: {
    getParty(id) {
      PartyDataService.get(id)
          .then(response => {
            this.currentParty = response.data;
            console.log(response.data);
          })
          .catch(e => {
            console.log(e);
          });
    },
    updatePublished(status) {
      var data = {
        id: this.currentParty.id,
        name: this.currentParty.name,
        description: this.currentParty.description,
        published: status
      };

      PartyDataService.update(this.currentParty.id, data)
          .then(response => {
            this.currentParty.published = status;
            console.log(response.data);
          })
          .catch(e => {
            console.log(e);
          });
    },
    updateParty() {
      PartyDataService.update(this.currentParty.id, this.currentParty)
          .then(response => {
            console.log(response.data);
            this.message = 'The Party was updated successfully!';
          })
          .catch(e => {
            console.log(e);
          });
    },
    deleteParty() {
      PartyDataService.delete(this.currentParty.id)
          .then(response => {
            console.log(response.data);
            this.$router.push({ name: "parties" });
          })
          .catch(e => {
            console.log(e);
          });
    }
  },
  mounted() {
    this.message = '';
    this.getParty(this.$route.params.id);
  }
};
</script>

<style>
.edit-form {
  max-width: 300px;
  margin: auto;
}
</style>

And this is my PartyDataService in case you need it:如果您需要,这是我的 PartyDataService:

import http from "../http-common";

class PartyDataService {
    getAll() {
        return http.get("/parties");
    }

    get(id) {
        return http.get(`/parties/${id}`);
    }

    create(data) {
        return http.post("/parties/", data);
    }

    update(id, data) {
        return http.put(`/parties/${id}`, data);
    }

    delete(id) {
        return http.delete(`/parties/${id}`);
    }

    deleteAll() {
        return http.delete(`/parties`);
    }
    findByTitle(title){
        return http.get(`/tutorials?title=${title}`)
    }
}

export default new PartyDataService();

After some more research I think this file is important to upload: My http-common.js:经过更多研究后,我认为上传这个文件很重要:我的 http-common.js:

import axios from "axios";

export default axios.create({
    baseURL: "http://localhost:8080/",
    headers: {
        "Content-type": "application/json",

    }

});

Adding this to the code above in headers:将此添加到标题中的上述代码中:

'Access-Control-Allow-Origin' : '*',
 "Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,PATCH,OPTIONS"

Does not work.不工作。 It only makes another working get operation on another Vue page in my project not work anymore.它只会使我项目中另一个 Vue 页面上的另一个工作获取操作不再工作。

Extra info:额外信息:

  • I am already using an access-control-allow-origin extension (in case it is information you need)我已经在使用 access-control-allow-origin 扩展(如果它是您需要的信息)
  • My backend RESTful API is made with Spring boot (gradle)我的后端 RESTful API 是用 Spring 引导(gradle)制作的
  • I am just learning about Vue and stuff, so could you explain your answer as simple as possible?我只是在学习 Vue 和其他东西,所以你能尽可能简单地解释你的答案吗?

If you need extra files or information you can ask me and I will add it into the post.如果您需要额外的文件或信息,您可以问我,我会将其添加到帖子中。

Thanks in advance!提前致谢!

Cors is a mechanism in browsers to make sure that your application is allowed to use that API (definition can be a little bit wrong but it boils down to that). Cors 是浏览器中的一种机制,可确保您的应用程序被允许使用该 API (定义可能有点错误,但归根结底)。 Which means that your server must send the headers described in your answer:这意味着您的服务器必须发送您的答案中描述的标头:

header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")

Your client (vuejs application) doesn't need to do anything related to CORS.您的客户端(vuejs 应用程序)不需要做任何与 CORS 相关的事情。 It is your backend server that needs to send these headers.需要发送这些标头的是您的后端服务器。

In your question you do not have the backend server you are using (Laravel, express, spring, etc...) so it is hard to guide you to the right direction without knowing you backend technologies在您的问题中,您没有正在使用的后端服务器(Laravel、express、spring 等),因此在不了解后端技术的情况下很难引导您走向正确的方向

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查 - Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check "CORS 预检请求未通过访问控制检查:它没有 HTTP ok 状态" - CORS preflight request doesn't pass access control check: It does not have HTTP ok status CORS 策略阻止访问:对预检请求的响应未通过访问控制检查 - Access blocked by CORS policy: Response to preflight request doesn't pass access control check CORS 策略已阻止从源“http://localhost:4200”访问“http://localhost:8080”处的 XMLHttpRequest - Access to XMLHttpRequest at 'http://localhost:8080 from origin 'http://localhost:4200' has been blocked by CORS policy CORS 策略已阻止从源“http://localhost:8080”访问“http://localhost:8092/URL”处的 XMLHttpRequest - Access to XMLHttpRequest at 'http://localhost:8092/URL' from origin 'http://localhost:8080' has been blocked by CORS policy 对预检请求的响应未通过访问控制检查:不存在“Access-Control-Allow-Origin”标头 - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present CORS 策略已阻止从源“http://localhost:62521”访问“localhost:3000/users”处的 XMLHttpRequest - Access to XMLHttpRequest at 'localhost:3000/users' from origin 'http://localhost:62521' has been blocked by CORS policy 选项而不是Post:对预检请求的响应未通过访问控制检查。 - Option instead of Post: Response to preflight request doesn't pass access control check. 预检请求未通过访问控制检查 - Preflight request doesn't pass access control check 飞行前响应没有HTTP正常状态。 403在Angular 6中 - Response for preflight does not have HTTP ok status. 403 in Angular 6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM