简体   繁体   中英

Vue.js GET request to API gets blocked by CORS

I am trying to fetch data from an API in Vue.js and console.log the response but I get a CORS problem, most specifically: from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I read that I need to create a vue.config.js file, I did but nothing changed, I also tried just using the fetch api, maybe I am making http calls the wrong way in Vue, how can I get my data and resolve this error?

Here is my component:

<template>
  <div class="container">
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "HelloWorld",
  methods: {},
  mounted() {
    axios
      .get(
        "https://base-url"
      )
      .then(response => console.log(response));
  }
};
</script>

and my vue.config.js :

module.exports = {
    devServer: {
        proxy: 'base-url',
    }
}

I think you may need to set up a middleware in the endpoint you are calling such as following:

// ACCEPTING CROSS SITE REQUESTS
api.use(cors());
api.use((req, res, next)=>{
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Please try to add this to your endpoint API you are calling from so that new calls can be authorized.

Your should have 'Access-Control-Allow-Origin: ' Header

so make sure that your [api base url] returns this header to make your browser allow your request to go through without being (as way of protection)

More information about Access-Control-Allow-Origin

An Example in PHP:

<?php
  header('Access-Control-Allow-Origin: *') // to allow all sites
  ... the rest of the code

Do you have the header configuration setup for cors in your vue.config? Should look something like this.

在此处输入图像描述

In the recent versions of vuejs, for example if the remote api is at http://localhost:9002/tasks then use server config.

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    proxy: {
      '/tasks': 'http://localhost:9002'
    }
  }
})

I found out what I was doing wrong, after setting up the proxy I had to change my get request to

mounted() {
    axios
      .get(
        "http://localhost:8080/https://base-url"
      )
      .then(response => console.log(response));

That fixed the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM