跨域,前端

一、跨域问题与解决

  • 在前后端分离开发中,前端页面运行在某个域名(如 `http://localhost:8080`),后端服务运行在另一个域名(如 `http://localhost:3000`)。当前端页面通过 js(如 `axios`)向后端发送请求时,浏览器会执行同源策略,限制跨域请求,从而导致请求失败。
  1. 使用 `koa-cors` 解决跨域问题

```js

app.use(cors());

```

二、前端页面数据加载与渲染

  1. 页面加载事件:绑定 `load`,渲染

```js

window.addEventListener('load', function () {

});

```

(二)请求后端接口

  1. 使用 `axios` 向后端接口发送请求,获取数据库中的数据。

```js

// `url` 是后端服务的地址,例如 `http://localhost:3000`。

axios.get(`${url}/blogs`).then(res => {

// 处理响应数据

});

```

  1. 数据渲染到页面

```js

this.document.querySelector('tbody').innerHTML = arr.map(item => `

<tr>

<td>${item.id}</td>

<td>${item.title}</td>

<td>${item.author}</td>

<td>

<input type="button" value="编辑" οnclick="btnEdit(${item.id})">

<input type="button" value="删除" οnclick="btnDel(${item.id})">

</td>

</tr>

`).join('');

```

相关推荐
codingWhat12 小时前
能效平台设计方案(打通gitlab和飞书)
后端·node.js·koa
见过夏天2 天前
Node.js 常用命令全攻略
node.js
前端双越老师3 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen3 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
donecoding4 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js
Flynt5 天前
npm v12 来了:allowScripts 默认关闭,我的项目差点跑不起来
安全·npm·node.js
叫我Paul就好5 天前
尝试 Node 搭建后端-开发框架
node.js
风止何安啊7 天前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js
糖拌西瓜皮7 天前
Node.js核心模块实战:文件、路径、HTTP与流处理
javascript·node.js
糖拌西瓜皮7 天前
Node.js工程化实践:包管理、TypeScript配置与代码质量
typescript·node.js