You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML/JS开发Google Sheets CRUD遇401未授权错误求助

Google Sheets CRUD功能401未授权问题求助

我用HTML和JavaScript开发了一个CRUD功能,用来展示、编辑和删除Google Sheets中的条目。配置好所有连接参数后,读取数据正常,但执行编辑、删除等写操作时,始终返回**error 401(Unauthorized)**错误。以下是我的实现代码及删除操作时的报错信息,请求技术帮助(已隐去敏感凭证):

<!DOCTYPE html>
<html>
<head>
    <title>Google Sheets Reader</title>
    <style>
        /* 表格样式 */
        table {
            border-collapse: collapse;
            width: 100%;
        }

        table, th, td {
            border: 1px solid black;
            padding: 8px;
        }

        /* 图片样式 */
        img.dalkia-logo {
            max-width: 100px; /* 根据需求调整最大宽度 */
            height: auto;
            display: block;
            margin: 0 auto; /* 水平居中图片 */
        }
    </style>
</head>
<body>
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Logo_Dalkia.svg/langfr-210px-Logo_Dalkia.svg.png" alt="Dalkia Logo" class="dalkia-logo">
    <table id="dataTable">
        <!-- 表格内容将动态填充 -->
    </table>
    <button id="addButton">添加一行</button>

    <script>
        const spreadsheetId = '';
        const apiKey = '';
        const sheetName = '';
        let data; // 存储获取到的数据

        // 从Google Sheets获取数据的函数
        function fetchData() {
            fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${sheetName}?key=${apiKey}`)
                .then(response => response.json())
                .then(responseData => {
                    data = responseData; // 将获取到的数据存储到全局变量
                    const dataTable = document.getElementById('dataTable');
                    dataTable.innerHTML = '';

                    data.values.forEach(row => {
                        const newRow = dataTable.insertRow();
                        row.forEach(cellValue => {
                            const newCell = newRow.insertCell();
                            newCell.textContent = cellValue;
                        });

                        // 为每行添加编辑和删除按钮
                        const editButton = document.createElement('button');
                        editButton.textContent = '编辑';
                        editButton.addEventListener('click', () => editRow(row));

                        const deleteButton = document.createElement('button');
                        deleteButton.textContent = '删除';
                        deleteButton.addEventListener('click', () => deleteRow(row));

                        newRow.appendChild(editButton);
                        newRow.appendChild(deleteButton);
                    });
                })
                .catch(error => console.error(error));
        }

        // 编辑行的函数
        function editRow(rowData) {
            const updatedData = prompt('输入用逗号分隔的新数据:', rowData.join(', '));
            if (updatedData !== null) {
                const newData = updatedData.split(', ');
                const rowIndex = data.values.indexOf(rowData);
                data.values[rowIndex] = newData;

                // 更新Google Sheets中的数据
                updateGoogleSheets(data.values);

                // 刷新表格
                fetchData();
            }
        }

        // 删除行的函数
        function deleteRow(rowData) {
            if (confirm('确定要删除这一行吗?')) {
                const rowIndex = data.values.indexOf(rowData);
                data.values.splice(rowIndex, 1);

                // 更新Google Sheets中的数据
                updateGoogleSheets(data.values);

                // 刷新表格
                fetchData();
            }
        }

        // 更新Google Sheets数据的函数
        function updateGoogleSheets(updatedData) {
            const requestBody = {
                values: updatedData
            };

            fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${sheetName}?valueInputOption=RAW&key=${apiKey}`, {
                method: 'PUT',
                body: JSON.stringify(requestBody),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (response.status === 200) {
                    console.log('数据更新成功');
                } else {
                    console.error('数据更新失败');
                }
            })
            .catch(error => console.error(error));
        }

        // 为"添加一行"按钮添加事件监听
        document.getElementById('addButton').addEventListener('click', () => {
            // 在此处实现添加新行的逻辑
        });

        // 页面加载时获取数据
        fetchData();
    </script>
</body>
</html>

删除操作时的报错信息:

Failed to load resource: the server responded with a status of 401 ()
(index):118 数据更新失败
(anonyme) @ (index):118
(index):107
PUT https://sheets.googleapis.com/v4/spreadsheets/1tUabe1-BO5iVMICKJ3dUxu5lCrHD6tIhueys9YUnFe0/values/R%C3%A9ponses%20au%20formulaire%201?valueInputOption=RAW&key=AIzaSyBvmaKwkRf_nRZbql5Vuib53cJuUCgBssA 401 (Unauthorized)
updateGoogleSheets @ (index):107
editRow @ (index):80
(anonyme) @ (index):58
(index):118 数据更新失败
(anonyme) @ (index):118
Promise.then (asynchrone)
updateGoogleSheets @ (index):114
editRow @ (index):80
(anonyme) @ (index):58

内容的提问来源于stack exchange,提问作者Saif Ejjilali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:14:52