96SEO 2026-08-06 21:10 3
当下 AI 生图、多模态图文生成应用越来越普遍,很多前端同学会尝试直接在项目中对接大模型接口。这篇文章以Vite 原生 JS 项目为例,完整实现对接通义千问图文生成接口。同时解决API Key 安全存储、浏览器跨域、异常容错等实战问题,从环境配置到代码落地一步步讲解,适合前端入门对接 AI 接口的开发者参考。
本次项目基于 Vite 搭建纯前端项目。主要能力:

再看项目技术栈,Vite + 原生 JavaScript + Fetch + 通义千问开放网站接口
使用 Vite 官方脚手架快速创建原生 JS 项目:
npm init vite
# 按照指引选择 Vanilla。完成项目初始化
最终基础目录结构:
qwen-image-demo/
├── .env.local # 本地环境变量
├── .gitignore # 忽略敏感文件配置
├── index.html # 项目入口页面
├── package.json
└── src/
└── main.js # 主要业务逻辑、接口请求代码
Vite 原生项目默认入口,无需额外改造,代码如下:
If you directly put your AI platform's API key in JavaScript,after building project it will be fully exposed in front‑end source code。making it easy for ors to steal and cause account usage charges. Therefore environment variables are required.
VITE_;说起来,orwise Vite cannot recognize it.;no spaces around equals sign.
VITE_QWEN_API_KEY=你的通义千问API_KEY
You can read environment variables using Vite's special syntax:
const apiKey = import.meta.env.VITE_QWEN_API_KEY;console.log,
Add rules to ignore .env files so y never get committed accidentally:
# Ignore all env files
.env*
.env.local*
.env.development.local*
.env.production.local*
# Add any or patterns as needed
This part demonstrates how to combine multiple reference images and a textual instruction into one request while handling loading state。error catching,and field fallback to make your code robust.
// Read API key from environment variables
const apiKey = import.meta.env.VITE_QWEN_API_KEY;// Get container element
const root = document.querySelector;其实,// Show loading message initially
root.innerHTML = '
正在生成图片。请稍候...
';/**
* Call Qwen multimodal image generation endpoint
* @returns {Promise} Image URL or null on failure
*/
const generateImage = async => {
try {
const res = await fetch(
'https这方面,//dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation',{
method这方面,'POST',headers: {
'Content-Type': 'application/json'。'Authorization': `Bearer ${apiKey}`,},body: JSON.stringify({
"model": "qwen-image--pro","input": {
"messages":
}
]
},// Parameters can be customized
// For demo we set n=1
// size can be set to specific resolution if needed
// e.g.,size: {"width":"1024","height":"1024"}
// Here we keep it flexible
})
}
);
if throw new Error;const data = await res.json;console.log,// Fallback logic – find first image item safely
const imageItem =
data?.output,按理说,.choices?.,话说回来,.message?
.content,.find;if throw new Error;return imageItem.image;} catch {
console.error;其实,root.innerHTML =
'
' +
至于`生成失败。${err.message}` +
'
';return null,}
};
/**
* Render generated image into page
* @param {string} imageUrl Image URL returned from API
*/
const renderImage = => {
if return;root.innerHTML =
<,img src="${imageUrl}" alt="AI generated image"
style="max-width:100%;按理说,height:auto;" />
;},
// Entry point of application
const main = async => {
const imgURL = await generateImage;renderImage,};
main;/**
* User Pain Points addressed:
* - API Key leakage – store key in .env.local and ignore via .gitignore.
* - CORS errors – handled by proxy or backend relay .
* - Unexpected response shape – try/catch and safe navigation prevent UI crashes.
* - Loading feedback – simple loading message before rendering result.
*/
代码逻辑解析
-
环境变量读取:从 import.meta.env 中获取密钥,并拼接至 Authorization 头部。
-
Fetch 请求:SEND POST 请求到 Qwen 的多模态生成接口。
-
多模态入参:
messages 数组可同时包含多张图片和文本描述,实现复杂场景生成。
-
Error handling:
try/catch 捕获网络错误或字段缺失,并给出友好提示。
-
A/B 渲染:
renderImage 将得到的 URL 插入 DOM,并包装成可开始下载链接。
-
User pain point: 前端直接暴露 API Key 与跨域限制是最常见且痛苦的问题,这段代码正好解决了它们。
-
User pain point: 接口返回结构不确定时往往导致页面崩溃。我们用安全导航和 fallback 防止此类情况。
-
User pain point: 开发期间需要即时看到加载状态并调试错误,上述实现满足此需求。
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback