Use Axios in Vue to implement cross-domain requests and set the format of the returned data in JSON format, not JSONP format

Source: Internet
Author: User
Tags domain server

Using Axios in Vue to implement cross-domain requests

Demand analysis: In the project needs to crawl QQ music song list of data, due to request the data address URL=HTTPS://C.Y.QQ.COM/SPLCLOUD/FCGI-BIN/FCG_GET_DISS_BY_TAG.FCG. From the official website of QQ music you can see that the domain name in Referer in the request header is y.qq.com (the domain name of the sending request page), and the host domain name is c.y.qq.com (the domain name of the requested page), because the two are not the same, so the front-end can not directly send a request to the QQ server to get data. This time requires the server to do a proxy: that is, the front-end to its domain server to send a request, and then the domain server to the QQ music domain server to send the request, the domain server to get the data, and then back to the front end.

Use Axios in Vue to implement cross-domain requests. Axios is a promise-based HTTP library that can be used in browsers and node. js.

Chinese Handbook

GitHub Address

Here's how to implement a proxy using Axios

1. First use NPM to install Axios to a local project

    1. NPM Install Axios--save

2, then, the introduction of Axois in Build/webpack.dev.conf.js

3. Add Property function before (app) {} in Devserver object in Build/webpack.dev.conf.js file

The complete code is as follows

  1. Before (APP) {
  2. Because the request referer and host are different, so the front end can not get the data, need to do a proxy
  3. The backend sends requests to the server that has the data, gets the data, and then the front-end requests that data from its own servers.
  4. The AJAX request is implemented here using Axios: Axios is a promise-based HTTP library that can be used in browsers and node. js
  5. Create an XMLHttpRequest object in the browser, create an HTTP request from node. js
  6. App.get ('/api/getdisclist ', (req, res) => {//The path here is the URL to send the request to the front end
  7. Let url = ' HTTPS://C.Y.QQ.COM/SPLCLOUD/FCGI-BIN/FCG_GET_DISS_BY_TAG.FCG
  8. Axios send a GET request, you can configure Config yourself
  9. Axios.get (URL, {
  10. Headers: {
  11. ' Referer ': ' https://c.y.qq.com/',
  12. ' Host ': ' C.y.qq.com ',
  13. },
  14. The params is the URL parameter that is about to be sent with the request, unformatted object/urlsearchparams object
  15. Params:req.quest
  16. }). Then ((response) => {
  17. Res.json (Response.data)//Return Data
  18. }). catch ((Error) => {
  19. Console.log (Error)
  20. })
  21. })
  22. }

4. Write JS code on the front

1) Define a recommend.js file that reads as follows

  1. Import Axios from ' Axios '
  2. Get data for a song list
  3. Because the proxy request is used here, the front-end request is changed to an AJAX request
  4. Export function Getdislist () {
  5. Const URL = '/api/getdisclist '
  6. Const data = {
  7. Picmid:1,
  8. Rnd:Math.random (),
  9. g_tk:5381,
  10. Jsonpcallback: ' Getplaylist ',
  11. Loginuin: ' 0 ',
  12. hostuin:0,
  13. Format: ' JSON ',
  14. Incharset: ' UTF8 ',
  15. Outcharse: ' Utf-8 ',
  16. notice:0,
  17. Platform: ' Yqq ',
  18. neednewcode:0,
  19. categoryid:10000000,
  20. Sortid:5,
  21. sin:0,
  22. Ein:29
  23. }
  24. Using AJAX requests, here with Axios
  25. Return Axios.get (URL, {
  26. Params:data
  27. }). Then (res) => {
  28. Successfully returns a Promise object
  29. Return Promise.resolve (Res.data)
  30. }). catch ((Error) => {
  31. Console.log (Error)
  32. })
  33. }

2) write the following in the <script> of the Recommend.vue file:

  1. <script>
  2. Import {getdislist} from '. /.. /api/recommend '
  3. Export Default {
  4. Get Data
  5. Created () {
  6. This._getdisclist ()
  7. },
  8. Methods: {
  9. Get data for a single list of songs
  10. _getdisclist () {
  11. Getdislist (). then (res) => {
  12. Console.log (RES)
  13. })
  14. }
  15. }
  16. }
  17. </Script>

5, the content of the browser console.log () output

    1. ' Musicjsoncallback ({"Code": 0, "subcode": 0, "message": "", "Default": 0, "data": {"UIn": 0, "CategoryId": 0, "sortId": 5, " Sum ": 0," sin ": 0," ein ": 0," list ": []}) '

That is, the output is the JSONP format, which is the string

6. Set the returned data to the JSON format: Since the returned data is a string, it can be intercepted, using Json.parse () to convert the string into JSON form

  1. <script>
  2. Import {getdislist} from '. /.. /api/recommend '
  3. Export Default {
  4. Get Data
  5. Created () {
  6. This._getdisclist ()
  7. },
  8. Methods: {
  9. Get data for a single list of songs
  10. _getdisclist () {
  11. Getdislist (). then (res) => {
  12. Console.log (RES)
  13. Let num1 = res.indexof (' (')
  14. Let num2 = res.indexof (') ')
  15. Let resultdata = json.parse (res.substring (NUM1 + 1, num2))
  16. Console.log (typeof (Resultdata))
  17. Console.log (Resultdata)
  18. })
  19. }
  20. }
  21. }
  22. </Script>

The output is as follows

The above is probably the use of Axios to achieve the service side of the proxy request

Use Axios in Vue to implement cross-domain requests and set the format of the returned data in JSON format, not JSONP format

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.