簡體   English   中英

如何使用JavaScript存儲網頁/網頁中的數據?

[英]How to store a web page/ data from web page using JavaScript?

我想使用JavaScript將頁面Tableau Public Gallery feed以JSON格式本地存儲。 我一直在尋找腳本和代碼片段,但是由於每次運行代碼都會遇到相同的錯誤,因此找不到任何有用的信息。

Access to XMLHttpRequest at 'https://public.tableau.com/en-us/s/gallery/feed' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

以下是我當前正在使用的代碼。

  $.ajax({

     url:"https://public.tableau.com/en-us/s/gallery/feed",
     method: 'GET',
     dataType:'JSON',
     headers: {
         'Access-Control-Allow-Origin': '*'
     },
     success: function(response) {
         console.log(response);
     }
});

我也嘗試過使用POSTMAN。 它還給出了無法得到任何響應的錯誤。 是出於Tableau網站的限制,還是我做錯了什么。

PS:我正在嘗試在Angular 7項目中實現這一點。

除非https://public.tableau.com/en-us/s/gallery/feed在響應中提供Access-Control-Allow-Origin ,否則您將無法從瀏覽器的其他域執行此操作。 相反,我建議設置一個后端端點(也許通過NodeJS),該端點將調用此端點而不是前端,然后從代碼中調用該端點。 在后端,您將不會遇到Access-Control-Allow-Origin錯誤,這就是為什么我建議您將其作為代理。

如果決定使用NodeJS作為后端,則可以執行以下操作:

運行npm install --save express以安裝Express for Node(一個Node服務器框架)

創建一個像這樣的結構:

在此處輸入圖片說明

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
    <script>
        $.ajax({
            url: "/api/tableau-gallery-feed",
            method: 'GET',
            success: function (response) {
                console.log(response);
            }
        });
    </script>
</body>
</html>

index.js

var express = require('express')
var https = require('https')
var app = express()

app.use(express.static('public'))

app.get('/api/tableau-gallery-feed', function (req, res) {
    https.get('https://public.tableau.com/en-us/s/gallery/feed', function (data) {
        data.setEncoding('utf8')
        let rawData = ''
        data.on('data', function (chunk) {
            rawData += chunk
        })
        data.on('end', function () {
            res.end(rawData)
        });
    })
})

app.listen(8888, () => console.log('Server started.'))

然后運行node index.js來啟動服務器

轉到localhost:8888以查看您的頁面,如果您檢查控制台,則應記錄數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM