求带认证与参数的JavaScript启动Jenkins任务示例
当然可以!我来给你几个实用的JavaScript示例,实现和curl POST请求等价的Jenkins任务触发,同时搞定认证和参数传递。先理清楚核心逻辑,再上具体代码。
核心原理先搞懂
Jenkins触发参数化任务的核心API端点是:http://你的Jenkins地址/job/任务名称/buildWithParameters
- 认证:用Basic Auth,把你的Jenkins用户名和API Token拼接成
username:token,转成Base64字符串放在请求头的Authorization里 - 参数传递:把任务需要的参数以表单数据(form-data)的形式提交,和你用curl的
-d参数逻辑完全一致
先给你看对应的curl命令做对比,方便你对应理解:
curl -X POST "http://jenkins.example.com/job/MyTestJob/buildWithParameters" \ -u "jason:my-api-token-123" \ -d "ENV=production" \ -d "DEPLOY_VERSION=v1.2.3"
示例1:用原生Fetch API(浏览器/Node.js v18+通用)
如果不想引入额外库,原生fetch就能搞定。注意Node.js和浏览器环境处理Base64的方式略有不同:
// 配置信息,替换成你的实际内容 const jenkinsConfig = { url: 'http://jenkins.example.com/job/MyTestJob/buildWithParameters', username: 'jason', token: 'my-api-token-123', params: { ENV: 'production', DEPLOY_VERSION: 'v1.2.3' } }; // 构造认证头 const authHeader = `Basic ${Buffer.from(`${jenkinsConfig.username}:${jenkinsConfig.token}`).toString('base64')}`; // 如果是浏览器环境,替换上面的行: // const authHeader = `Basic ${btoa(`${jenkinsConfig.username}:${jenkinsConfig.token}`)}`; // 构造表单数据 const formData = new FormData(); Object.entries(jenkinsConfig.params).forEach(([key, value]) => { formData.append(key, value); }); // 发送请求 fetch(jenkinsConfig.url, { method: 'POST', headers: { 'Authorization': authHeader // 注意:不需要手动设置Content-Type,fetch会自动处理form-data的边界 }, body: formData }) .then(response => { if (response.ok) { console.log('任务触发成功!'); // Jenkins会返回201 Created,响应头里的Location是任务构建的URL console.log('构建URL:', response.headers.get('Location')); } else { console.error('任务触发失败,状态码:', response.status); return response.text().then(text => console.error('错误信息:', text)); } }) .catch(error => console.error('请求出错:', error));
示例2:用Axios库(更简洁,适合Node.js/前端项目)
如果你的项目已经在用Axios,代码会更简洁,Axios会帮你处理很多细节:
const axios = require('axios'); // Node.js环境,前端直接引入即可 // 配置信息 const jenkinsConfig = { url: 'http://jenkins.example.com/job/MyTestJob/buildWithParameters', username: 'jason', token: 'my-api-token-123', params: { ENV: 'production', DEPLOY_VERSION: 'v1.2.3' } }; // 发送请求(两种参数传递方式二选一) // 方式1:参数放在URL查询字符串中 axios.post(jenkinsConfig.url, null, { auth: { username: jenkinsConfig.username, password: jenkinsConfig.token // Jenkins的API Token可以直接当密码用 }, params: jenkinsConfig.params }) // 方式2:参数放在表单数据中 // axios.post(jenkinsConfig.url, jenkinsConfig.params, { // auth: { // username: jenkinsConfig.username, // password: jenkinsConfig.token // }, // headers: { // 'Content-Type': 'application/x-www-form-urlencoded' // } // }) .then(response => { console.log('任务触发成功!'); console.log('构建URL:', response.headers.location); }) .catch(error => { console.error('任务触发失败:', error.response?.data || error.message); });
几个关键注意事项
- API Token获取:登录Jenkins后,进入个人设置(右上角头像→设置),找到“API Token”选项,生成一个新token保存好,绝对不要泄露!
- 任务配置:你的Jenkins任务必须开启“参数化构建过程”,并且添加了对应的参数(比如ENV、DEPLOY_VERSION),否则传递的参数会被忽略
- 上下文路径:如果你的Jenkins部署时有上下文路径(比如
http://jenkins.example.com/my-jenkins/),记得在URL里加上,比如http://jenkins.example.com/my-jenkins/job/MyTestJob/buildWithParameters - 权限检查:确保你的Jenkins用户有触发该任务的权限(比如“Build”权限)
内容的提问来源于stack exchange,提问作者Jason
相关产品推荐
相关产品推荐

