已拦截跨源请求:同源策略禁止读取位于 file:///modify-table 的远程资源。(原因:CORS 请求不是 http)续上一篇文章的解决方法

5 篇文章 0 订阅
3 篇文章 0 订阅

        这个错误是由于CORS(跨源资源共享)策略导致的,因为浏览器不允许前端代码从file:///协议访问http://localhost:3000。为了避免这个问题,你需要使用HTTP服务器来提供HTML文件。

你可以使用Node.js中的Express来同时提供HTML文件和处理API请求。以下是完整的示例,包括提供HTML文件的部分。

1.创建项目目录结构

project

├── server.js
└── public
    └── index.html

 2.修改 server.js 文件

const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();

app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public'))); // 设置静态文件目录

// 配置MySQL连接
const db = mysql.createConnection({
    host: 'localhost',
    user: 'your_username',
    password: 'your_password',
    database: 'your_database'
});

// 连接到MySQL
db.connect((err) => {
    if (err) {
        throw err;
    }
    console.log('MySQL connected...');
});

// 创建一个简单的API来处理数据库操作
app.post('/modify-table', (req, res) => {
    let sql = req.body.query;
    db.query(sql, (err, result) => {
        if (err) {
            res.status(500).send(err);
        }
        res.send(result);
    });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

3. 创建 public/index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modify MySQL Table</title>
</head>
<body>
    <h1>Modify MySQL Table</h1>
    <form id="query-form">
        <textarea id="query" placeholder="Enter SQL query" rows="4" cols="50"></textarea><br>
        <button type="submit">Submit</button>
    </form>
    <div id="result"></div>

    <script>
        document.getElementById('query-form').addEventListener('submit', function (e) {
            e.preventDefault();
            const query = document.getElementById('query').value;
            fetch('/modify-table', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ query })
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('result').textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                document.getElementById('result').textContent = 'Error: ' + error;
            });
        });
    </script>
</body>
</html>

4. 启动Node.js服务器

在项目根目录下运行:

node server.js

5. 访问页面

打开浏览器,访问http://localhost:3000。现在你应该能够正确地通过表单发送请求并修改MySQL数据库。

备注

  • 确保MySQL服务器正在运行,并且你有一个可用的数据库。
  • your_usernameyour_passwordyour_database替换为实际的MySQL凭据。

这种方法使用了Node.js服务器来提供HTML文件,从而避免了CORS问题。确保在实际应用中加入适当的安全验证和权限控制,以防止SQL注入和其他安全问题。

As an AI language model, I am not able to perform installations on any machine or device. However, I can provide you with the steps to install Homebridge on Docker, as mentioned in the Homebridge GitHub page: 1. Install Docker on your machine. You can follow the official Docker installation guide for your specific operating system from the Docker website. 2. Create a new directory on your machine where you want to store your Homebridge configuration and plugins. You can name it whatever you like. For example, we will name it "homebridge". 3. Open a terminal or command prompt window and navigate to the directory you just created. 4. Create a new file named "config.json" in the directory. This file will contain your Homebridge configuration. You can copy and paste the sample configuration from the Homebridge GitHub page and modify it as per your requirements. 5. Create a new file named "Dockerfile" in the directory. This file will contain the Docker image build instructions. You can copy and paste the following code and modify the Docker image tag as per your requirements: ``` FROM oznu/homebridge:latest COPY config.json /homebridge/config.json ``` 6. Build the Docker image by running the following command in the terminal or command prompt window: ``` docker build -t <your_username>/homebridge . ``` Replace <your_username> with your Docker Hub username (if you have one) or any other name you want to use for the Docker image. 7. Run the Docker container by running the following command in the terminal or command prompt window: ``` docker run -d --restart always --name homebridge -p 51826:51826 -v /path/to/homebridge:/homebridge <your_username>/homebridge ``` Replace "/path/to/homebridge" with the absolute path to the directory you created earlier. This command will start the Homebridge Docker container, map the default Homebridge port 51826 to your machine's port 51826, and mount your Homebridge configuration and plugins directory to the container's /homebridge directory. 8. You can now access your Homebridge instance by opening the Home app on your iOS device and adding a new accessory. Homebridge should automatically appear as a bridge accessory. You can then add your Homebridge-compatible devices and control them through the Home app. Note: These steps are provided as a general guide only. You should always read and follow the official documentation and installation instructions provided by the Homebridge and Docker communities, and ensure you have a good understanding of the potential risks and limitations of using these technologies.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学不完了是吧

v我5块会的全告诉你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值