Configure the proxy and test the interface to implement Ajax cross-domain requests

It’s not all done yet!! The project address

In real development, browsers don’t allow cross-domain requests by default for security purposes, so how do we implement Ajax cross-domain requests?

Problem analysis:

  • All of the pages that have run so far are static pages

  • Next, test using wrapped Ajax interface request functions to retrieve data asynchronously

    // Start by introducing encapsulated interface functions in app.vue
    import {reqCategorys} from './api'
    // Then call the interface to test printing data
    export default {
      async mounted () {
        const result = await reqCategorys()
        console.log(result)
      },
      components: {
        FooterGuide
      }
    }
    Copy the code
  • GET http://local:4000/index_category 404(Not Found)

  • Remember that the back-end API port is 4000, and then modify the test in index.js under the API folder

    / / define BASE_URL
    const BASE_URL = 'http://local:4000'
    // Then change the URL of the requested interface
    export const reqCategorys = () = > ajax(BASE_URL + '/index_category')
    Copy the code
  • The access-Control-allow-Origin request is a cross-domain request

Configure the proxy and test the interface:

  • In addition to setting up ways for the server to allow cross-domain requests, you can configure the proxy to implement cross-domain requests
  1. Set the proxy configuration table in the index.js file under the project config folder
// Paths
// Static resources folder
assetsSubDirectory: 'static'.// Publish path
assetsPublicPath: '/'.// Proxy configuration table, where you can configure a specific request proxy to the corresponding API interface
// For example, 'localhost:8080/ API/XXX 'to 'www.example.com/api/xxx'
proxyTable: {
  '/api': { // Matches all request paths starting with '/ API '
  	target: 'http://localhost:4000'.// The base path of the proxy target
    // Secure: false, // This parameter needs to be configured for HTTPS interfaces
    changeOrigin: true.// Cross-domain support
    pathRewrite: { // Rewrite path: remove the starting '/ API 'from path
      '^/api': ' '}}},Copy the code
  1. Change the request path of the interface function in the API folder index.js

    // const BASE_URL = 'http://local:4000'
    const BASE_URL = '/api'
    
    export const reqAddress = geohash= > ajax(`${BASE_URL}/position/${geohash}`)
    export const reqCategorys = () = > ajax(BASE_URL + '/index_category')
    // The following modified interface is omitted...
    Copy the code
  2. The project NPM run dev needs to be restarted because the project config file has been modified

  3. {code: 0, data: Array(16)}