You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

将Twilio的cURL POST请求转换为Axios请求时遭遇415状态码错误

Fixing 415 Unsupported Media Type Error for Twilio Asset Upload via Axios

That 415 error usually pops up when the server doesn’t recognize the media type you’re sending, and in your case, there are a couple of misalignments between your Axios request and the original cURL command. Let’s break down the fixes step by step:

1. Wrong Authentication Approach

Your cURL uses -u for Basic Authentication, but your Axios code tries to pass username and password directly in headers—this isn’t how Basic Auth works here. Axios has a built-in auth config option that automatically generates the correct Authorization header for you.

2. Manual Content-Type Header Breakage

When sending FormData with Axios, don’t manually set the Content-Type header. Axios will automatically set it to multipart/form-data with the required boundary parameter. If you set it manually, you’ll omit this boundary, which the server needs to parse the form data correctly—this is a common cause of 415 errors.

3. Tweak the FormData Content Field

While JSON.stringify(mapping) is valid, ensure the file options are properly passed to the FormData.append method (some environments need explicit syntax for the options object).

Corrected Axios Code

const url = `https://serverless-upload.twilio.com/v1/Services/${service_uid}/Assets/${asset_uid}/Versions`;
const form = new FormData();

// Match the cURL form fields exactly
form.append('Path', 'mapping.json');
form.append('Visibility', 'private');
// Append JSON content with correct filename and content type
form.append('Content', JSON.stringify(mapping), {
  filename: 'mapping.json',
  contentType: 'application/json'
});

try {
  const response = await axios.post(url, form, {
    // Use Axios's native auth for Basic Authentication
    auth: {
      username: client.accountSid,
      password: client.password
    }
    // No manual Content-Type header needed—Axios handles this
  });
  console.log('Upload successful:', response.data);
} catch (error) {
  console.error('Upload failed:', error.response?.data || error.message);
}

Extra Checks for Node.js Environments

If you’re running this in Node.js, install the form-data package (npm install form-data) and import it, since Node’s native FormData behaves differently from browser implementations:

const FormData = require('form-data');

Also double-check that mapping is a valid JSON object before stringifying it—invalid JSON can cause hidden parsing issues on the server side.

This adjustment aligns your Axios request perfectly with the original cURL command, fixing the 415 error by sending the correct media type and authentication headers.

内容的提问来源于stack exchange,提问作者darkrai

火山引擎 最新活动