搭建前端vue,连接前后台

前言
上一篇博客我们创建好了自己的后台,那么基于前后端分离的一种情况下,我们需要做的是让前后台连接起来。
1、首先我们要创建自己的vue程序,那么这里我默认大家都搭建好了自己的vue环境,直接创建!

在你的目录下按住shift并右键点击“在此处打开powershell”,然后

vue init webpack +项目名字

然后姓名,接着按自己需求,我一边在install router是点击yes,其他地方点no
经过我们一番操作之后呢,vue的脚手架项目就搭建好了。

在你的终端

npm install

这个命令,然后
npm run dev
这个名字,然后点击就可以运行你的vue文件!

然后我们讲一讲springboot 跨域,在你的springboot后端里的com.example.demo下建立一个tool包,然后创建一个cors文件,

然后直接copy我的代码:

package com.example.demo.tool;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 解决跨域问题
 * @author chj
 * */
@Configuration
public class Cors {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否允许请求带有验证信息*/
        corsConfiguration.setAllowCredentials(true);
        /*允许访问的客户端域名*/
        corsConfiguration.addAllowedOrigin("*");
        /*允许服务端访问的客户端请求头*/
        corsConfiguration.addAllowedHeader("*");
        /*允许访问的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

这样你的前端项目就可以访问后台接口了,接下来讲一讲vue axios访问springboot接口

npm install axios

使用这个命令,然后在vue里面导入在这里插入图片描述
然后,在你的created里面,调用axios。

  created () {
    axios({
      method: 'post',
      url: 'http://localhost:8080/'
    }).then(res => {
      console.log(res)
    })
  }

对了,你需要在你的vue脚手架里配置一下前端的端口,
在config文件夹里的index.js文件,更改port为8081,接下来打开你的浏览器,输入http://localhost:8081

发布了20 篇原创文章 · 获赞 5 · 访问量 2082

猜你喜欢

转载自blog.csdn.net/qq_42859887/article/details/97394172
今日推荐