2022.06.07 Front-end-uniApp cross-domain solution

1.1. How to judge whether it is cross-domain?

这就是需要用跨域来请求数据的报错

        

insert image description here

Each uniApp project will have a manifest.json configuration file.

Copy the following string of code directly in manifest.json.

1.2. Then how should I use this cross-domain / how to use it on the interface?

Then each project will have an interface-encapsulated file, which is the configuration file for the centralized request interface. Or if you don’t have it, you need to write or find the code of the relevant files yourself, so it is very important to encounter a standard project example when learning, so no one will take us there to ask for this kind of standard project? Of course it is the github master. Then change the public address requested by the interface to your cross-domain name/proxy name.

 The util.js sample encapsulation interface is as shown in the figure, and it is imported in main.js after writing.

 The following is the interface package file of my project, and then import this file in main.js to use the interface.

api.js

page.vue and then directly use the encapsulated request method on the page, checkLogin is the name of the encapsulated api interface, as shown in the figure:

 Another way is not to encapsulate the interface, and use axios to directly request the interface to be written on the page.

In this way, when the project requests the interface, it will automatically realize cross-domain.

 Note: The slash in front of api is very important. If you don’t write this slash, it will be judged by the browser as a direct access to the local address plus the interface, and then it will prompt the interface 404 error that the interface cannot be found, and it will directly access loaclhost + file root directory + interface address . http://localhost:8080/pages/index/api/t/wtdk/mobileVerifyApi

And using the leading slash will visit: http://localhost:8080/api/t/wtdk/mobileVerifyApi

Extended error avoidance: When we write the interface address and do not use cross-domain, some projects directly use the ip public address, such as: 192.168.127.0. When splicing the interface, many people will carelessly write it as 192.168.127.0:8080/t /wtdk/mobileVerifyApi, because there is no / at the beginning, it will be judged by the browser as a direct access to localhost:8080/***/192.168.127.0:8080/t/wtdk/mobileVerifyApi, resulting in a 404 error on the interface, so you forgot to write it http://, the correct way to write http://192.168.127.0:8080/t/wtdk/mobileVerifyApi, http:// is the same as "/". There is no need to write http:// as the beginning when cross-domain, because the cross-domain public address has already been written, so you need to use "/" as the beginning to avoid being misjudged by the browser.

Guess you like

Origin blog.csdn.net/m0_46551050/article/details/124019110