背景:123网盘中存了很多音乐文件,我希望对外提供一个链接,可以让一些音频播放器使用, 我不希望暴露webdav相关信息
一、WebDAV 核心基础:认证与访问原理
-
WebDAV 认证方式(Basic 认证) 123 网盘 WebDAV 采用 HTTP Basic 认证,这是最基础的认证方式,核心逻辑是: 账号密码拼接成 账号:密码 格式的字符串; 对拼接后的字符串做 Base64 编码; 最终在 HTTP 请求头中携带 Authorization: Basic + 编码结果
-
123 网盘 WebDAV 基础信息 服务器地址:webdav.123pan.cn/webdav 核心交互逻辑:通过 HTTP 方法(GET/POST/PUT/DELETE)操作文件,比如 GET 请求获取文件 / 目录信息、302 重定向返回文件真实访问链接。
基础实现:
jsconst express = require('express');
const axios = require('axios');
const path = require('path');
const app = express();
const PORT = 3000;
// 中间件
app.use(express.json());
app.use(express.static(path.join(__dirname)));
// WebDAV 认证信息
const authHeader = {
'authorization': 'Basic xxxxxxxx='
};
/**
* 获取 302 重定向后的真实 URL
*/
async function getRedirectUrl(url) {
try {
const response = await axios.get(url, {
headers: authHeader,
maxRedirects: 0,
validateStatus: (status) => status >= 200 && status < 400
});
if (response.status === 302 && response.headers['location']) {
return response.headers['location'];
}
return null;
} catch (error) {
if (error.response?.status === 302) {
return error.response.headers['location'];
}
throw error;
}
}
/**
* 获取播放链接 API
*/
app.post('/api/get-play-url', async (req, res) => {
try {
const { mp3name } = req.body;
const fileUrl = getRealUrl(mp3name)
const playUrl = await getRedirectUrl(fileUrl);
if (playUrl) {
res.json({
success: true,
playUrl: playUrl,
originalUrl: fileUrl
});
} else {
res.json({
success: false,
error: '未检测到重定向'
});
}
} catch (error) {
console.error('获取播放链接失败:', error.message);
res.status(500).json({
success: false,
error: error.message
});
}
});
// 启动服务器
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
这样前端通过调用 : 你自己的服务:端口/api/get-play-url , 入参mp3name ,就能得到这个文件的播放地址,并且123网盘相关配置都在服务端,不对外暴露