NodeJS调用Tableau REST API上传数据源返回406错误该如何处理
问题根因
- 请求头
Content-Type配置错误:你提交的是多段(multipart)格式的请求体,但错误将Content-Type设置为了application/xml;charset=UTF-8,Tableau服务端无法识别该请求格式,因此返回406错误。 - 手动拼接multipart请求体容易出现格式错误(比如多余空格、换行符不符合要求),稳定性差。
修改方案
直接使用request库原生的formData配置项处理多段请求,无需手动构造请求体和设置boundary,修改后的代码如下:
const request = require('request') const fs = require('fs') const options = { url: 'https://prod-apnortheast-a.online.tableau.com/api/3.12/sites/578341b7-325c-4dda-be08-ff0b10c4b18c/datasources', headers: { Authorization: 'Bearer xxxxxxxxxxxxxx' }, formData: { // 第一部分:请求元数据 request_payload: { value: `<tsRequest> <datasource name="datasource-name" description="datasource-description"> <connectionCredentials name="xxxx@abc.com" password="xxxxxx"/> <project id="96ec15ee-eef1-41ac-beda-1f03d9209305" /> </datasource> </tsRequest>`, options: { contentType: 'text/xml' } }, // 第二部分:数据源文件 tableau_datasource: { value: fs.createReadStream('./你的数据源文件路径.tds'), // 测试场景也可直接填写示例文本内容 options: { filename: "datasource-file-name.tds", // 注意要带正确的文件后缀,比如.tds/.hyper/.tdsx contentType: 'application/octet-stream' } } } } function callback (error, response, body) { if (error) { console.log(error) } console.log( body, response.headers, response.statusCode) } request.post(options, callback)
关键修改点说明
- 删除了请求头中错误的
Content-Type和手动设置的boundary参数,request库会自动根据formData内容生成符合规范的multipart/form-data请求头和boundary。 - 用
formData结构拆分请求的元数据部分和文件部分,避免手动拼接格式错误。 - 数据源文件名补充对应后缀,符合Tableau上传要求。
内容的提问来源于stack exchange,提问作者Mayank Patel
相关产品推荐
相关产品推荐

