赞
踩
走了很多弯路,总结出来的,保姆级别教学
直接带你使用,跟着我走,不会报错,如果不行,你来打我。
在请求时,如果出现了以下情况中的任意一种,那么它就是跨域请求:
跨域问题是指在浏览器环境下,当一个网页的脚本试图访问不同源(域名、协议或端口)的资源时,会发生跨域请求。这种问题主要是由于浏览器的同源策略导致的,该策略是为了防止恶意网站获取用户的敏感信息或进行攻击1。跨域问题出现的具体原因包括:
1. 域名不同:浏览器会限制不同域名之间的资源访问。
2. 端口不同:同源策略也包括端口号,因此不同端口的访问也会导致跨域问题。
3. 协议不同:如http和https之间的协议不同也会引发跨域问题2。
1、打开cmd窗口,将npm包换为淘宝镜像。
npm config set registry https://registry.npm.taobao.org
2、执行npm install -g @vue/cli命令,全局安装脚手架。
3、切换到你要创建项目的目录,然后使用命令创建项目,运行vue create xxx(xxx代表你要创建的项目的名字)。
4、在创建文件的目录下运行npm run serve,得到网址后打开即可看到类似hello world的案例。
1、安装 : win+R 打开终端或命令行窗口,输入命令npm install axios
2、使用:
用WebStorm或者Visual Studio Code打开项目 找到main.js
加入 红色部分
- import { createApp } from 'vue'
- import App from './App.vue'
- import axios from 'axios'
-
- const app = createApp(App);
-
- app.config.globalProperties.$http = axios
- app.mount('#app')
然后找到项目的 vue.config.js
加入
- const { defineConfig } = require('@vue/cli-service')
- module.exports = defineConfig({
- transpileDependencies: true,
- devServer: {
- host: '127.0.0.1', // 此前端项目的IP地址
- port: 8081, // 此前端项目的端口号
- open: true, //表示在启动开发服务器时,会自动打开浏览器并访问指定的地址
- proxy: {
- '/api': {
- target: 'http://127.0.0.1:8080/', //接口域名
- changeOrigin: true, //是否跨域
- ws: true, //是否代理 websockets
- secure: true, //是否https接口
- pathRewrite: {
- '^/api': '' //假如我们的地址是 /api/member/getToken 会转化为 /member/getToken
- }
- }
- }
- }
-
- })
找到 HelloWorld.vue
把<template>里面的其余的都删掉,就留这么点用来测试
- <template>
- <div class="hello">
- <h1 @click="getName()">{{ msg }}</h1>
- </div>
- </template>
script部分
- <script>
- export default {
- name: 'HelloWorld',
- props: {
- msg: String
- },
- methods:{
- async getName(){
- this.$http.get('/api/member/getToken').then(response => {
- // 请求成功处理
- console.log(response.data);
- }).catch(error => {
- // 请求失败处理
- console.log(error);
- });
- }
- }
- }
- </script>
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.CorsRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- /**
- * @Author: xhj
- * @Date: 2023/10/24/13:47
- * @Description:
- */
- @Configuration
- public class CustomCorsConfig {
-
- @Bean
- public WebMvcConfigurer corsConfigurer(){
- return new WebMvcConfigurer() {
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**")
- .allowedOrigins("http://localhost:8081") // 允许的来源域名,* 表示允许所有域名
- .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
- // .allowedHeaders("Content-Type", "X-Requested-With") // 允许的请求头
- .maxAge(3600); // 允许的缓存时间,单位为秒
- }
- };
- }
- }
最后运行 成功发送请求
npm run serve
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。