匠人学院 JR Academy
  • Position

    Where am I now, and where should I go?

    How your job is changing, where your experience can take you and what you still need for a target role, worked out from what you have actually done. Free, and the full result needs no sign-up.

    Analyse my career and skills

    Look up a career

    Will AI replace my job?AI impact and transition paths for common careersNew jobs in the AI eraWhat they do, what they need, how to move in

    Focused tools

    AI Engineer interview readiness30 timed questions on what you still need before interviewsCareer personality testDirections that suit how you workReturning to China checkJob prospects in China by school, major and graduation date

    AI coach

    Talk to your AI coachStill unsure after your result? Talk through what is holding you back
  • Core courses

    AI Engineer BootcampEngineering bootcamp from LLM apps to agentsAI Engineer Full-Stack Project Class16 weeks · RAG and full-stack AI projectsVibe Coding Masterclass8 weeks · direct agents to build and ship a productAI Essentials10 hours · use AI for email, reports, data and copyAI Office Automation Course8 weeks · help a whole company adopt AIOne-Person Company (OPC) Bootcamp15 weeks in person · build a one-person company with AIAll courses →

    AI engineering

    Machine Learning & Data Engineering Full-Stack ClassAI Agent & MCP Project BootcampAI Engineer Core TechniquesAI Engineer FoundationsAI Engineer Advanced: RAG to Agents and TuningClaude Code TasterAll AI engineering courses →

    AI at work

    AI Coding for everyoneClaude Code One-Day Masterclass (Non-Technical)Enterprise AI Automation BootcampAI Marketing BootcampAI Risk, Governance and Audit CourseOpenClaw 4-Week Personal AI Assistant BootcampAll AI-at-work courses →

    Career development

    AI Product Manager (BA) Bootcamp + InternshipAustralia IT Interview BootcampAustralia IT Technical Interview BootcampAustralia IT Resume BootcampAustralia Big Tech Job Search BootcampAustralia IT Career Planning BootcampAll career courses →

    Learn free first

    Vibe CodingAI for office workPrompt MasterAI EngineerAI data analysisResource centerInstructorsAll learning paths →
  • Evidence

    What will convince an employer?

    Certifications, projects, team work and competition entries, collected into one portfolio.

    See the portfolio

    Certifications

    Cert Master · all certificationsPrep and mock exams for AWS, Azure, GCP, Claude and moreAWS CLF-C02Entry-level AWS cloud certificationAWS SAA-C03Entry certification for cloud architectsClaude certificationsAnthropic Claude certification seriesAll certifications →

    Projects and team work

    P3 team projectsBuild a project with real teammates in a simulated team workflowP3 project experienceThe parts of a P3 project that go on your resumeDemo DayProject showcaseP3 certificatesProof once a project is completeAll of P3 →

    Competitions and work

    HackathonsBuild something against the clockSubmit your workAdd your project to the showcaseCareerOS portfolioDo tasks in the desktop app; your results become portfolio pieces
    Cert MasterBrowser extension, app and mini programScreenshot a question for analysis and practise anywhereAbout Cert Master
  • Connect

    How do I get myself in front of employers?

    Resume, interviews, referrals and mentors. See how far you are from the target role first, then decide what to fix.

    Start with Jobpin

    Resume and openings

    Graduate careersGraduate preparation across Australia, China, Malaysia, Singapore, the US and UKJobpinAI job search workspace: resume, roles, applicationsAI resumeRewrite your resume against a job descriptionReferralsRoles shared by students and mentorsOpportunitiesInternships, projects and collaborationsOffer boardOffers students have received

    Interviews

    AI Engineer interview guideSeven areas, with worked examplesFDE interview guideFive rounds, from scoping to the customer roundAI mock interviewPractise by text or voice and see the gapsInterview storiesReal interview experiencesSystem Design handbookPrepare for system design interviewsAll interview prep →

    Mentors

    1:1 mentorsBook AI, career and technical mentors by the hourGroup tutoringShare a tutor with a few others and pay less eachCareer coachingResume, interview and direction packages
    Jobpin desktopOne workspace for the whole job searchOrganise real experience and refine resume versions for target roles on macOS or Windows.About Jobpin
BusinessMembershipDownload CareerOS
0
匠人学院 JR Academy

Follow Us

linkedinfacebooktwitterinstagramyoutube

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png
Airbotix · AI learning & creation for kids Another Life · AI story game
Products46

CareerOS and tools

  • CareerOS
  • Cert Master
  • Jobpin
  • Jobpin web
  • Jobpin report
  • Jobpin desktop download
  • My job search reports
  • Buy report credits
  • Jobpin billing
  • AI Toolbox
  • AI Skill Marketplace

Membership

  • Membership
  • AI membership

Courses

  • Bootcamps
  • Training Camp
  • Kanban learning
  • AI Builder course
  • MCP course
  • NotebookLM workshop
  • Business Analyst course
  • Web Full-Stack Bootcamp
  • DevOps Bootcamp
  • Data Engineering Bootcamp
  • Data Analysis Bootcamp
  • Coding for Beginners
  • Algorithm Bootcamp

Career services

  • Graduate careers
  • Graduate careers in Australia
  • Graduate careers in China
  • Graduate careers in Malaysia
  • Graduate careers in Singapore
  • Graduate careers in the US
  • Graduate careers in the UK
  • 1:1 coaching
  • Career coaching
  • AI Engineer VIP
  • BA & PM Internship
  • Data Science Internship
  • Data Analysis Internship
  • Marketing Internship
  • Resume Review
  • Interview Coaching
  • Job Application Service
  • Job Monitoring
  • LinkedIn Management
  • LinkedIn Networking
Library57

Learning paths

  • All Learning Paths
  • AI Engineer
  • Context Engineering
  • Vibe Coding
  • Prompt Master
  • AI Builder
  • AI Product Manager
  • Python Basics
  • AI Productivity
  • AI Data Analysis
  • AI Finance
  • AI Content Creation
  • AI Image Creation
  • Frontend Development
  • Hermes Agent
  • OpenClaw Local Agent

Interactive labs

  • Prompt Lab
  • Frontend Lab
  • JavaScript Lab
  • Python Lab
  • AWS Lab
  • Azure Lab
  • LLM Lab
  • Git Lab

Reference and guides

  • Resources
  • Wiki
  • Cheat sheets
  • Roadmaps
  • AI roadmaps
  • Videos
  • Ebooks
  • Blog
  • Interview handbook
  • Mock exams
  • Free resources

Cities

  • Sydney
  • Melbourne
  • Brisbane
  • Adelaide
  • Singapore
  • Kuala Lumpur
  • London
  • New York
  • San Francisco
  • Los Angeles
  • Seattle
  • Toronto
  • Vancouver

Immigration

  • Australia Immigration
  • Skilled Visa 189/190/491
  • Employer Sponsored 482/186/494
  • Business Visa 188/888
  • UK Immigration
  • US Immigration
  • Canada Immigration
  • Singapore immigration
  • Malaysia immigration
Business20

For business

  • AI for Business
  • Business portal sign-in
  • Corporate Training
  • Internship Partnership
  • Recruitment Partnership
  • Enterprise (EN)

Metatree AI Lab

  • Metatree AI Lab (Chinese)
  • AI solutions (Chinese)
  • Digital employees (Chinese)
  • Case studies (Chinese)
  • Metatree AI Lab
  • AI services
  • Digital employees
  • Case studies

AI education for kids

  • Airbotix — AI Learning & Creation for Kids
  • AU Family Resource Hub
  • NAPLAN Report Guide
  • My School Data Guide
  • Sydney Private School Fees 2026
  • Kids Coding Programs
About15

Company

  • About Us
  • Our Mentors
  • Become a Mentor
  • Metaverse Classroom
  • JR Careers
  • Another Life — AI Story Game
  • Contact Us

Help and policies

  • FAQs
  • Terms & Conditions
  • Privacy Policy
  • Cancellation & Refund Policy
  • Site map

Friend links

  • CS Browser

Contact

  • hello@jiangren.com.au
  • 0421-672-555

Offices

Level 10b, 144 Edward Street, Brisbane CBD (Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
45A13, Block B, Oriental Hope Tianxiang Plaza, 500 Tianfu Avenue Middle Section, Wuhou District, Chengdu, Sichuan, China
Business Hub, 155 Waymouth St, Adelaide SA 5000
Disclaimer
footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

All content on the JR Academy website, including course materials, logos, and information provided, is protected under Australian intellectual property laws. Unauthorized use, sale, distribution, reproduction, or modification is strictly prohibited. Violations may result in legal action. By accessing our website, you agree to respect our intellectual property. JR Academy Pty Ltd reserves all rights, including patents, trademarks, and copyrights. Any infringement will be subject to legal prosecution. View Terms of Service

© 2017-2026 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572

HomeLearnCoursesCerts
  1. Home
  2. Learn
  3. Blog
  4. n8n 工作流自动化实战手册 — 进阶技巧与常见问题
JR Academy · BlogCareer insights

n8n 工作流自动化实战手册 — 进阶技巧与常见问题

Code Node 深度使用、错误处理、生产部署要点,以及 FAQ

Published2026-11-30
Reading time2 min
Author

Contents

  • Code Node:写真实代码
  • 处理复杂数据转换
  • 使用 npm 包
  • Python Code Node
  • 错误处理
  • 方式一:Error Trigger 工作流
  • 方式二:节点级别的 Try/Catch
  • 方式三:Code Node 里 try-catch
  • Webhook 安全配置
  • 生产部署要点
  • 环境变量管理
  • 定期备份
  • 性能优化
  • 常见问题(FAQ)
  • 学习资源

n8n 管理面板

掌握了基础节点之后,这些技巧能让你的工作流更健壮、更高效。

Code Node:写真实代码

n8n 的 Code Node 是它区别于 Zapier 最大的武器。支持完整的 JavaScript(Node.js 18)和 Python,能 require npm 包。

处理复杂数据转换

// 场景:把嵌套的 API 响应铺平为二维表格
const input = $input.first().json;
const users = input.data.users;

return users.flatMap(user => 
  user.orders.map(order => ({
    json: {
      userId: user.id,
      userName: user.name,
      orderId: order.id,
      amount: order.amount,
      date: new Date(order.createdAt).toLocaleDateString('zh-CN')
    }
  }))
);

使用 npm 包

在 Code Node 里可以直接 require 已安装的包(n8n 内置了常用库):

// 日期处理
const { DateTime } = require('luxon');
const formatted = DateTime.now().setZone('Asia/Shanghai').toFormat('yyyy-MM-dd HH:mm');

// 加密
const crypto = require('crypto');
const hash = crypto.createHmac('sha256', 'secret').update($json.data).digest('hex');

// JSON Schema 校验
const Ajv = require('ajv');
const ajv = new Ajv();
const valid = ajv.validate({ type: 'object', required: ['email'] }, $json);

Python Code Node

# n8n 也支持 Python(需要服务器安装 Python)
import json
from datetime import datetime

items = _input.all()
results = []

for item in items:
    data = item.json
    results.append({
        'json': {
            'processed_at': datetime.now().isoformat(),
            'original': data,
            'word_count': len(data.get('content', '').split())
        }
    })

return results

错误处理

方式一:Error Trigger 工作流

创建一个独立的"错误处理工作流",所有工作流的报错都汇集到这里:

  1. 新建 workflow,添加 Error Trigger 节点(而不是普通 trigger)
  2. 连接 Slack 节点,发送报警通知
  3. 在每个生产工作流的 Settings 里,设置 Error Workflow 指向这个工作流
Error Trigger
    ↓
Slack: "⚠️ 工作流 {{ $json.workflow.name }} 报错
        错误: {{ $json.execution.error.message }}
        时间: {{ $now.format('YYYY-MM-DD HH:mm') }}
        执行ID: {{ $json.execution.id }}"

方式二:节点级别的 Try/Catch

在 Settings 里开启每个节点的 Continue on Fail,然后用 IF 节点检查是否有错误:

HTTP Request(Continue on Fail: ON)
    ↓
IF: {{ $json.error }} 存在
  ├── True → 记录错误到数据库
  └── False → 继续正常流程

方式三:Code Node 里 try-catch

try {
  const response = await fetch($json.url);
  const data = await response.json();
  return [{ json: { success: true, data } }];
} catch (error) {
  return [{ json: { success: false, error: error.message } }];
}

Webhook 安全配置

生产环境的 Webhook 要做鉴权,防止被随意调用。

方式一:Header 鉴权

在 Webhook 节点开启 Header Auth:

Authentication: Header Auth
Name: X-Webhook-Secret
Value: your-secret-token-here

调用方需要在请求 Header 里加 X-Webhook-Secret: your-secret-token-here,否则 403。

方式二:验证 GitHub/Stripe 的签名

// Code 节点:验证 GitHub Webhook 签名
const crypto = require('crypto');
const signature = $json.headers['x-hub-signature-256'];
const payload = JSON.stringify($json.body);
const secret = 'your-github-webhook-secret';

const expected = 'sha256=' + crypto
  .createHmac('sha256', secret)
  .update(payload)
  .digest('hex');

if (signature !== expected) {
  throw new Error('Invalid signature — 请求被拒绝');
}

return $input.all(); // 验证通过,继续流程

生产部署要点

环境变量管理

敏感配置通过环境变量注入,不要硬编码在工作流里:

# docker-compose.yml 的 environment 部分
- N8N_ENCRYPTION_KEY=your-32-char-encryption-key  # 必须设置
- DB_TYPE=postgresdb                               # 使用 PG 存储工作流
- DB_POSTGRESDB_HOST=postgres
- DB_POSTGRESDB_DATABASE=n8n
- DB_POSTGRESDB_USER=n8n_user
- DB_POSTGRESDB_PASSWORD=secure_password
- WEBHOOK_URL=https://n8n.yourcompany.com

在工作流里引用环境变量:

{{ $env.MY_API_KEY }}

定期备份

# 备份 n8n 数据(包含所有工作流、credentials、执行历史)
docker exec n8n n8n export:workflow --all --output=/tmp/workflows.json
docker exec n8n n8n export:credentials --all --output=/tmp/credentials.json
docker cp n8n:/tmp/workflows.json ./backups/

性能优化

  • 执行历史保留天数:EXECUTIONS_DATA_MAX_AGE=30(默认保留所有,数据库会很大)
  • 并发执行数:N8N_CONCURRENCY_PRODUCTION_LIMIT=20
  • Queue Mode:高并发场景用 Redis Queue 模式,支持多 worker 水平扩展

常见问题(FAQ)

Q: n8n 支持多少并发执行?

默认单进程模式没有硬限制,取决于服务器性能。生产推荐用 Queue Mode(Redis + 多 worker),可以无限水平扩展。

Q: Webhook 在本地跑,外部服务怎么访问?

用 ngrok 或 Cloudflare Tunnel 把本地端口暴露到公网:

ngrok http 5678
# 得到类似 https://abc123.ngrok.io 的地址
# 在 n8n 里设置 WEBHOOK_URL=https://abc123.ngrok.io

Q: Credential 怎么在多个 workflow 里共享?

Credential 是全局的,创建一次后所有 workflow 都能选择使用,不需要重复填写。Credential 数据加密存储(用 N8N_ENCRYPTION_KEY 加密)。

Q: 工作流的版本控制怎么做?

用 n8n 内置的 Source Control 功能(Git 集成),Settings → Source Control → 连接 Git 仓库,可以把工作流定义 push 到 Git,实现版本控制和团队协作。

Q: 如何调试 Expression 表达式?

在节点配置面板,Expression 输入框旁边有一个小眼睛图标,点击可以实时预览该表达式在当前数据下的计算结果,不需要跑整个工作流。

Q: n8n 能替代自建微服务吗?

对于内部工具和轻量级集成完全可以。生产级的高吞吐量场景(每秒数千请求)还是需要专用的微服务,n8n 更适合运营自动化、数据同步、通知推送这类场景。


学习资源

资源 链接
官方文档 docs.n8n.io
工作流模板库(900+) n8n.io/workflows
社区论坛 community.n8n.io
AI 工作流专区 n8n.io/workflows/categories/ai
Level 1 官方课程 docs.n8n.io/courses/level-one
Author
Share or copy the link
← Previous articlen8n 工作流自动化实战手册 — AI Agent 实战:用 n8n 构建智能工作流Next article →n8n 工作流自动化实战手册 — HTTP Request 节点与 API 集成实战

Related articles

🇦🇺测一下:袋鼠国码农能当FDE吗?

2026-12-01

Monash 研究:肠道酸度是膳食纤维降血压的关键;AI 搬运新闻冲击维州选举信息;MPAC 公布 2027 演出季

2026-12-01

Adelaide 物理学家获 $250,000 总理科学奖;全球葡萄酒消费六十年降四分之一;残障师范生实习障碍研究

2026-12-01

DVA-C03今日上线首发 · Google Cloud AI Agent认证完整解析 · AZ-401本月GA替代AZ-400

2026-12-01

Anthropic推迟下一代模型并调百人做安全,AWS推出AI办公三件套,Google让用户单独关掉AI训练

2026-12-01

GitHub Copilot 实战指南 — Copilot AI Code Review:30 秒让 AI 帮你审 PR,三档深度随需切换

2026-11-30
View all articles →

Done reading? Next steps

Not sure what to learn next? Tell us where you are

Tell us what you do now and where you want to go. See your gaps in skills, evidence, experience, expression and positioning, and what to work on first. No sign-in needed.

Compare with my situation
  • SkillAI Engineer Bootcamp13 weeks, 12 Theory + 13 Practice live classes. You build one Agent system across Context, RAG, Tools, Memory and production Evals. Built for Applied AI and Agent Engineer roles.See the program →
  • PositioningLearning roadmaps by roleFrontend, backend, data, AI and more, laid out stage by stage in the order to learn them.All roadmaps →
  • ExpressionTry an AI mock interviewPick a role and run a mock interview to practise explaining your experience and projects.Practise now →

Not sure what to do next?

Take this page's topic with you and see where your gaps are.

Compare with my situation
JR Academy
AI learning for the global Chinese community
BootcampsFree resourcesLearn AICareer coaching
精选推荐
AI Career Impact Map
Assess career exposure and explore transition paths and learning options
Popular tool
AI & Data Bootcamps
Build your skills through structured courses and hands-on projects
Popular courses
1:1 Career Coaching
Work with an experienced mentor on your resume and interview preparation
Career coaching
Custom Corporate Training
AI training tailored to your team
Business services
Popular tags
Vibe CodingAI codingCursorClaudeJob searchPromptFrontend developmentBackend development
Subscribe to updates

Receive AI learning resources, technical tutorials and career advice by email.

We respect your privacy and do not send spam.