Note: after the background service changes, you need to restart the service; after the front-end configuration file changes, you need to run the command npm run dev again
I. use express to provide background service and output interface
Background directory structure:
main.js
var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World'); }) app.get('/getUserInfo', function(req, res, next){ //Interface for foreground call, http://127.0.0.1:8888/getUserInfo console.log('get The user request data is:'); console.log(req.query); res.json({ code:200, data:{ message:'Hello' }, message:'success' }); }); var server = app.listen(8888, function () { var host = server.address().address var port = server.address().port console.log(host,port) console.log("your application is running on http://localhost:8888") })
---Explanation:
(1) app.get() means to receive all the get requests from the front end. Similarly, app.post(),app.delete() means to accept the post requests and delete requests from the front end respectively.
(2) app.get(path, callback [, callback...]): for parameter passing, the first parameter is the path, and the later parameters are all callback functions. You can put one or more callback functions. Generally, only one callback is used. In this example, only one callback is used. The official explanation for this method is: Routes HTTP GET requests to the specified path with the specified callback functions, which means "send http get request to the specified path with the specified callback method". Generally speaking, it performs some operations on the interface represented by the path parameter, which are written in the second parameter, the callback function.
(3) the second parameter in app. Get() -- callback function: the callback function takes three parameters. According to the unwritten writing convention of most people, the three parameters are req, res, next. The first parameter represents the http request object, the second parameter represents the response object, and the third parameter is the next function, indicating that the control is handed over to the next middleware. Next is a bit complicated. Just remember that after a request is finished, don't write next(), the common res.send(),res.json() belong to the end of the request, and don't write next() later
(4)res.json(obj) means to return a JSON object, and the detailed data of the object is what is in brackets.
II. Vue cli scaffold is used in the front end
Front end directory structure:
1. Solve cross domain problems first
Add the following agent to proxyTable in module.exports object in config/index.js file:
proxyTable: { '/gsafetyapi': { target: 'http://127.0.0.1:8888 / ', / / the service address to be proxy, add http changeOrigin: true, //Cross domain secure: false, //If it is an https interface, you need to configure this parameter timeout: 480000, pathRewrite: { '^/gsafetyapi': '' //Here it is understood that gsafetyapi is used to replace the address in target } }, },
2. Package axios and interface address set
New folder plugins
http.js
import axios from 'axios'; import apiConfig from "./api.js" import qs from 'qs' axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? 'gsafetyapi' : ''; //Add agent in development, no agent in production environment // Request interception axios.interceptors.request.use(config => { // 1. This location is the last configuration before the request // 2. Of course, you can also add the user authorization information required by your backend in this location return config }, error => { return Promise.reject(error) }) // Response interception axios.interceptors.response.use(response => { // Request successful // 1. Customize your interception according to your project requirements // 2. Then return the data return response; }, error => { // request was aborted if (error && error.response) { switch (error.response.status) { case 400: // Your handling of 400 errors\ break case 401: // Handling 401 errors break default: // If none of the above is handled return Promise.reject(error); } } }) export default { /** * get request * @param api_name Interface routing * @param params Interface parameters * @param time If the requested call costs more than 'time', the request will be interrupted * @returns {AxiosPromise<any>} */ // get(apiKey, data) { // return axios.get(apiConfig[apiKey], data); // }, get(api_name, params, time) { let url = apiConfig[api_name]; return axios({ method: 'get', url: url, params: params, timeout: time || 60000, }) }, /** * post request * * @param api_name Interface routing * @param params Interface parameters * @param time If the requested call costs more than 'time', the request will be interrupted * @returns {AxiosPromise<any>} */ post(api_name, params, time) { let url = apiConfig[api_name]; return axios({ method: 'post', url: url, params: qs.stringify(params), timeout: time || 60000, }) }, }
Encapsulating api files
api.js
export default { getCompanyDepartmentTree: "/api/v1/user-center-service/companyDepartment/getCompanyDepartmentTree", //Get organization structure data getUserInfo:"/getUserInfo" }
3. Global registration encapsulated axios
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. // The build version of Vue to be loaded using the import command has been set in webpack.base.conf using alias (run only or stand-alone) import Vue from 'vue' import App from './App' import router from './router' import http from '../plugins/http' Vue.config.productionTip = false Vue.prototype.$http = http; /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
4. Interface adjustment: http://127.0.0.1:8888/getUserInfo
created () { this.$http .get("getUserInfo",{name:'kate'}).then(res => { console.log(res) }); }