【问题标题】:Vuejs with Axios - getting ''cross-origin" error when using get request [duplicate]带有Axios的Vuejs-使用获取请求时出现“跨域”错误[重复]
【发布时间】:2019-03-15 13:03:28
【问题描述】:

我的 vue 项目位于这个 url “http://localhost:8081/”。

我想连接到另一个网址“http://localhost:8082/Fleet-App/api/deptList”中的后端。

但是当我拨打电话时,我收到了这样的错误

无法加载http://localhost:8082/Fleet-App/api/deptList:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:8081' 因此不允许访问***"。

请帮我解决这个问题。

sample.vue

<template>
 <b-card>
    <h5 class="card-title">Outside Order</h5>
    <hr>
     <div class="form-group row">
    <label for="" class="col-sm-2 col-form-label">Order #</label>
    <div class="col-sm-2">
     <input class="form-control" type="text" placeholder="Default input">
    </div>

    <label for="" class="col-sm-2 col-form-label">Order Type</label>
    <div class="col-sm-2">
      <select class="form-control">
        <option>Bulk</option>
        <option>Container</option>
      </select>
    </div>

     <label for="" class="col-sm-2 col-form-label">Status</label>
    <div class="col-sm-2">
      <select class="form-control">
        <option>Active</option>
        <option>In-Active</option>
      </select>
    </div>
  </div>

  <div class="form-group row">
    <label for="" class="col-sm-2 col-form-label">Order Date</label>
    <div class="col-sm-2">
     <input class="form-control" type="text" placeholder="DD-MMM-YYYY">
    </div>
  </div>
 </b-card>
</template>

<script>
import {AXIOS} from '../../components/http-common'

export default {
  name: 'order',
  mounted(){
     AXIOS.get('/deptList')
      .then(response => {
        console.log(JSON.stringify(response.data))
      })
      .catch(e => {
        this.errors.push(e)
      })
   }
}
</script>

http-common.js

import axios from 'axios'

const API_URL = process.env.API_URL || 'http://localhost:3000/api/v1'

export const AXIOS = axios.create({
  baseURL: `http://localhost:8082/Fleet-App/api/`,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + localStorage.token,
    'Access-Control-Allow-Origin': '*',
    'Accept' : 'application/json, text/plain, */*',
    'Access-Control-Allow-Methods' : 'GET, PUT, POST, DELETE, OPTIONS',
    'Access-Control-Allow-Credentials' : true
  }
})

提前致谢。

【问题讨论】:

    标签: vue.js vuejs2 cors axios


    【解决方案1】:

    看起来您的服务器在响应您的请求时不包含 Access-Control-Allow-Origin 标头。如果缺少 Access-Control-Allow-Origin,CORS 请求将失败。

    以下是一些解释 CORS 工作原理的有用文章:

    基本上,问题出在服务器上,而不是在你的 vue.js 客户端上

    希望这会有所帮助!

    【讨论】:

    • 谢谢@Marco Dagrada。仅在服务器端出现问题。我在服务器中添加了 cors 过滤器。现在我可以连接位于不同端口的服务器
    猜你喜欢
    • 2021-03-05
    • 2020-06-07
    • 2018-03-28
    • 2020-07-18
    • 1970-01-01
    • 2021-11-26
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多