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

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

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

1.创建项目目录结构

project

├── server.js

└── public

└── index.html

2.修改 server.js 文件

javascript 复制代码
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 文件

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服务器

在项目根目录下运行:

html 复制代码
node server.js

5. 访问页面

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

备注

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

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

相关推荐
Java成神之路-4 分钟前
DNS 与 CDN 底层原理深度剖析:从域名解析到内容分发全链路解析
网络·网络协议·tcp/ip
清风徐来QCQ31 分钟前
js中的模板字符串
开发语言·前端·javascript
AI浩34 分钟前
UCAN:用于轻量级超分辨率中扩展感受野的统一卷积注意力网络
网络
SuperEugene1 小时前
Vue3 + Element Plus 表格实战:批量操作、行内编辑、跨页选中逻辑统一|表单与表格规范篇
开发语言·前端·javascript
极梦网络无忧1 小时前
基于 Vite + Vue3 的组件自动注册功能
前端·javascript·vue.js
echome8881 小时前
Python 异步编程实战:asyncio 核心概念与最佳实践
开发语言·网络·python
Predestination王瀞潞1 小时前
5.4.3 通信->WWW万维网内容访问标准(W3C):WWW(World Wide Web) 协议架构(分层)
前端·网络·网络协议·架构·www
喵喵爱自由2 小时前
Docker容器共享宿主机-安全网络
网络·安全·docker
星爷AG I2 小时前
15-6 威胁性信息(AGI基础理论)
网络·agi
软弹2 小时前
深入理解 React Ref 机制:useRef 与 forwardRef 的协作原理
前端·javascript·react.js