Node.js调用DeepL API POST请求报403,同凭据GET请求正常,求问题排查
问题原因
你的代码存在3个直接触发403错误的问题:
- 请求头声明的
Content-Type为application/x-www-form-urlencoded,但实际提交的body是JSON字符串,格式完全不匹配,DeepL服务端无法正确解析出你提交的auth_key参数,就会判定你没有提供有效凭据返回403。 - 手动写死了
Content-Length为固定值54,这个值和你实际提交的body长度大概率不一致,服务端会判定请求异常直接拦截。 - 你提到GET请求正常,是因为GET请求的参数直接拼接在URL里,不需要处理POST的body格式问题,所以凭据能被正常识别。
修正方案
你可以选择两种修改方式,任选其一即可:
方式1:保留JSON提交格式
删除没必要手动指定的Content-Length、Host请求头,修改Content-Type为JSON类型即可,fetch会自动生成正确的请求头参数:
app.get('/translate', (req, res) => { var textToTranslate = "Hello friend" const targetLanguage = "ES" var link = `https://api-free.deepl.com/v2/translate` var options = { method: 'POST', headers: { "Content-Type": 'application/json', "User-Agent": "YourApp", "Accept": "*/*", }, body: JSON.stringify({ 'auth_key': deeplAccessCode, 'text': textToTranslate, 'target_lang': targetLanguage }), } return fetch(link, options) .then((response) => { console.log(response) return response.json(); //Transform http body to json }) .then((json)=> { res.send(json) //return json to browser }) .catch(e => { console.log(e) return res.sendStatus(400); }); })
方式2:保留表单提交格式
把body改成和请求头匹配的表单格式即可:
app.get('/translate', (req, res) => { var textToTranslate = "Hello friend" const targetLanguage = "ES" var link = `https://api-free.deepl.com/v2/translate` var options = { method: 'POST', headers: { "Content-Type": 'application/x-www-form-urlencoded', "User-Agent": "YourApp", "Accept": "*/*", }, body: new URLSearchParams({ 'auth_key': deeplAccessCode, 'text': textToTranslate, 'target_lang': targetLanguage }), } return fetch(link, options) .then((response) => { console.log(response) return response.json(); //Transform http body to json }) .then((json)=> { res.send(json) //return json to browser }) .catch(e => { console.log(e) return res.sendStatus(400); }); })
内容的提问来源于stack exchange,提问作者Divine Ogbuefi
相关产品推荐
相关产品推荐

