如何为不同的域API设置Vue CORS? [英] How to Set up Vue CORS for different domain API?

查看:48
本文介绍了如何为不同的域API设置Vue CORS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试部署一个Vue应用程序,该应用程序具有单独的后端,并将托管在不同的域中.例如:

I' trying to deploy an Vue app which has a separate backend and which will be hosted in different domain. For example:

  1. meow.cat.xyz(应用程序)
  2. api.meow.cat.xyz(API)

现在,在 npm run build 之后,我尝试通过运行 serve -s dist 在本地预览它,并且该应用程序在localhost:5000处被切断.但是,问题在于它没有在当前端点(本地的 localhost:8000 和服务器的 api.meow.cat.xyz )上发送API请求.我尝试如下配置CORS

Now after npm run build I tried to preview it locally by running serve -s dist and the application is severing at localhost:5000. However the problem is it not sending API request at the current end point (which is localhost:8000 at local and api.meow.cat.xyz at server). I tried config CORS as following

vue.config.js

module.exports = {
  devServer: {
    port: process.env.VUE_APP_DEV_PORT,
    proxy: process.env.VUE_APP_API_ROOT_PATH,
  },
};

.env.development

VUE_APP_API_ROOT_PATH = 'http://localhost:8000/api'
VUE_APP_DEV_PORT = 3000

请注意,我正在使用axiox.这是我的axios设置.

Note that I'm using axiox. Here is my axios setup.

API.js

import axios from "axios";

const injectAccessToken = (config) => {
  const accessToken = localStorage.getItem("access_token");
  if (accessToken)
    config.headers.common["Authorization"] = `Bearer ${accessToken}`;
  return config;
};

const config = {
  baseURL: process.env.VUE_APP_API_ROOT_PATH,
};

const API = axios.create(config);

API.interceptors.request.use(injectAccessToken);

export default API;

并按以下方式使用

Login.vue

import API from "@/api/Api";

<script>
  const res= await API.post('login')
</script>

此解决方案尚无法使用.它在 http://localhost:5000 上的发送请求.重点是什么 ?请注意,我正在使用axios.预先感谢.

This solution is not working yet. Its sending request at http://localhost:5000. What's the point ? Note that I'm using axios. thanks in advance.

推荐答案

允许来自服务器的CORS请求

使用Access-Control-Allow-Origin标头,您可以指定可以使用您的API的来源.

With the Access-Control-Allow-Origin header, you can specify what origins can use your API.

app.get('/api', (req, res) => {
    res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.send({
        api: "your request."
    });
})

这篇关于如何为不同的域API设置Vue CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆