从零开始,构建电子地图网站:0_14_springboot跨域+vue+axios网络请求

别来无恙 提交于 2020-03-09 21:49:12

我们的程序是前后端分离的。

后端是springboot,在IDEA中启动GismapApplication.java,访问http://localhost:8080/history/geometry?category=prefpgn&start=-5000&end=-221,就能看到数据了。

前端是vue,cmd到vue-gismap下,npm run dev,访问http://localhost:8090/#/specialmap,就能看到页面了。

但是后端和前端的ip和port一样,不能在同一台主机中启动,所以要把前后端的端口号port设置成不同的,才能联调。

一、设置端口号

  1. 修改后端端口号

Springboot修改端口号;

D:\gismap\java\master\gismap\src\main\resources\application.yml

修改port即可,我把端口号由之前的8080,修改为了8081。

 

server:
 
port: 8081

#数据库配置
spring:
 
datasource:
   
#alibaba数据连接池
   
type: com.alibaba.druid.pool.DruidDataSource
   
#postgresql驱动
   
driverClassName: org.postgresql.Driver
   
#数据库地址、账号、密码
   
url: jdbc:postgresql://127.0.0.1:5432/postgres
   
username: postgres
   
password: 123456
   
druid:
     
#初始化连接大小
     
initial-size: 8
     
#最小空闲连接数
     
min-idle: 5
     
#最大连接数
     
max-active: 10
     
#查询超时时间
     
query-timeout: 6000
     
#事务查询超时时间
     
transaction-query-timeout: 6000
     
#关闭空闲连接超时时间
     
remove-abandoned-timeout: 1800
     
filters: stat,config

mybatis:
 
#sql映射文件
 
mapper-locations: classpath:mapper/*.xml
 
#model
 
type-aliases-package: com.history.gismap.model
#log日志配置
logging:
 
config: classpath:logback-boot.xml

 

 

  1. 修改前端端口号

修改vue端口号:

vue-gismap/config/index.js

修改port即可,我把8080改成了8082

 

'use strict'

// Template version: 1.3.1

// see http://vuejs-templates.github.io/webpack for documentation.

 

const path = require('path')

 

module.exports = {

  dev: {

 

    // Paths

    assetsSubDirectory: 'static',

    assetsPublicPath: '/',

    proxyTable: {},

 

    // Various Dev Server settings

    host: 'localhost', // can be overwritten by process.env.HOST

    port: 8082, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined

    autoOpenBrowser: false,

    errorOverlay: true,

    notifyOnErrors: true,

    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

 

   

    /**

     * Source Maps

     */

 

    // https://webpack.js.org/configuration/devtool/#development

    devtool: 'cheap-module-eval-source-map',

 

    // If you have problems debugging vue-files in devtools,

    // set this to false - it *may* help

    // https://vue-loader.vuejs.org/en/options.html#cachebusting

    cacheBusting: true,

 

    cssSourceMap: true

  },

 

  build: {

    // Template for index.html

    index: path.resolve(__dirname, '../dist/index.html'),

 

    // Paths

    assetsRoot: path.resolve(__dirname, '../dist'),

    assetsSubDirectory: 'static',

    assetsPublicPath: '/',

 

    /**

     * Source Maps

     */

 

    productionSourceMap: true,

    // https://webpack.js.org/configuration/devtool/#production

    devtool: '#source-map',

 

    // Gzip off by default as many popular static hosts such as

    // Surge or Netlify already gzip all static assets for you.

    // Before setting to `true`, make sure to:

    // npm install --save-dev compression-webpack-plugin

    productionGzip: false,

    productionGzipExtensions: ['js', 'css'],

 

    // Run the build command with an extra argument to

    // View the bundle analyzer report after build finishes:

    // `npm run build --report`

    // Set to `true` or `false` to always turn it on or off

    bundleAnalyzerReport: process.env.npm_config_report

  }

}

 

 

 

二、解决跨域问题

因为前后端端口号不一样,所以会遇到跨域问题。

会提示:No 'Access-Control-Allow-Origin' header is present on the requested resource

就是因为跨域,前端无法请求后端数据。

解决跨域问题也很简单。后端加一个注释就可以,@CrossOrigin。

D:\gismap\java\master\gismap\src\main\java\com\history\gismap\controller\MapController.java

package com.history.gismap.controller;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import com.history.gismap.model.GeometryModel;

import com.history.gismap.service.MapService;

import com.vividsolutions.jts.geom.Coordinate;

import com.vividsolutions.jts.geom.Geometry;

import lombok.extern.slf4j.Slf4j;

import org.geotools.geojson.geom.GeometryJSON;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;



import java.io.StringWriter;

import java.util.List;



@Controller

@RequestMapping(value = "/history")

@Slf4j

public class MapController {

    @Autowired

    private MapService mapService;

    /**

     * 根据表名和时间区间输出对象

     * @param category 表名简写

     * @param start 起始时间

     * @param end 终止时间

     * @return

     */

    @ResponseBody

    @GetMapping("/geometry")

    @CrossOrigin

    public JSONObject getPoint(@RequestParam("category") String category,@RequestParam("start") Integer start,@RequestParam("end") Integer end){

        try {

            List<GeometryModel> result=mapService.getDynastyGeom(category,start,end);

            JSONObject jsonObject=new JSONObject();

            jsonObject.put("number",result.size());

            JSONArray jsonArray=new JSONArray();

            GeometryJSON geometryJSON=new GeometryJSON();

            for (GeometryModel g:result) {

                JSONObject geom=new JSONObject();

                geom.put("gid",g.getGId());

                geom.put("namepy",g.getNamePy());

                geom.put("namech",g.getNameCh());

                geom.put("nameft",g.getNameFt());

                geom.put("presloc",g.getPresLoc());

                geom.put("typepy",g.getTypePy());

                geom.put("typech",g.getTypeCh());

                geom.put("levrank",g.getLevRank());

                geom.put("begyr",g.getBegYr());

                geom.put("begrule",g.getBegRule());

                geom.put("endyr",g.getEndYr());

                geom.put("endrule",g.getEndRule());

                geom.put("geosrc",g.getGeoSrc());

                geom.put("compiler",g.getCompiler());

                geom.put("gecomplr",g.getGecomplr());

                geom.put("checker",g.getChecker());

                geom.put("entdate",g.getEntDate());

                geom.put("begchgty",g.getBegChgTy());

                geom.put("endchgty",g.getEndChgTy());

                StringWriter writer = new StringWriter();

                geometryJSON.write(g.getGeometry(),writer);

                geom.put("geometry",JSONObject.parse(writer.toString()));

                jsonArray.add(geom);

            }

            jsonObject.put("list",jsonArray);

            log.info("入参类别:{},起始时间:{},截至时间:{}",category,start,end);

            return jsonObject;

        }catch (Exception e){

            log.error("程序错误类型:",e);

            return null;

        }

    }



}

 

 

三、vue+axios网络请求

  1. 安装模块

首先安装axios模块

npm install axios

 

2.axios get请求

一个非常简单的get请求,写在组件SpecialMap.vue里。

初始化加载getdata()函数,更新axiosdata数据,写在div中,vue用两个花括号{{}},在模板中引入数据。

 

 

<template>

  <div>

    {{axiosdata}}

    专题地图

  </div>

</template>

<script>

import axios from 'axios'

export default {

  data() {

    return {

      axiosdata: null

    }

  },

  methods: {

    getdata() {

      axios.get('http://localhost:8081/history/geometry?category=prefpgn&start=-5000&end=-221').then((response) => {

        this.axiosdata = response.data

        console.log(response.data)

      }).catch((response) => {

        console.log(response)

      })

    }

  },

  mounted() {

    this.getdata()

  }

}

 

</script>

 

 

 

 

模板搭建好了,leaflets能加载底图和覆盖物了,axios能和后端交互了,接下来要做的,就是把要实现的功能都实现了。

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!