gpt4 book ai didi

node.js - 内容类型为 : multipart/form-data Troubleshooting 的 NodeJS Post 请求

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:14 25 4
gpt4 key购买 nike

我正在尝试将 dataUrl 发送到客户端的服务器。

请求发送到一个 PHP 脚本,其中包含 Content-Type: multipart/form-data 和键/值消息正文 image=(dataUri string)

如果已成功接收,则会发回 10 位数字响应。如果不成功,则会发送错误响应。

我正在使用datauri module生成dataurl

如果我尝试使用以下命令通过终端执行此操作:

val=`cat dataUri.txt` #generated via datauri module
curl -X POST -F 'image='$val http://xxx.yyyyyyy.com:8082/server/post.php

我成功了。

当尝试使用node和http.request时,我惨败了:(。通过反复试验和大量谷歌搜索,我偶然发现了--trace-ascii,它为您提供了终端中通信的非常详细的故障。所以我一直在尝试有效地复制标题等,希望我能让它发挥作用。

我的请求代码目前如下所示:

    var body = 'image='+dataUri ;

postOptions = {

headers: {
'Content-Type': 'multipart/form-data; boundary=------------------------69b2c2b9c464731d' ,
'Content-Disposition': 'form-data; name="image"' ,
'Content-Length': Buffer.byteLength(body) ,
'Accept': '*/*' ,
'Expect': '100-continue'
} ,

host: 'xxx.yyyyyyy.com' ,
port: '8082' ,
path: '/server/post.php' ,
method: 'POST'
} ;

// Set up the request
post_req = http.request(
postOptions,
function(res) {
//
res.setEncoding('utf8') ;

res.on('data', function (chunk) {
console.log('Response: ' + chunk) ;
}) ;

}) ;

// post the data
post_req.write(body) ;
post_req.end() ;

每次都失败。我注意到的一件事:在终端中,内容长度数字比我在 Node 中使用 Buffer.byteLength 得到的数字大了几百个字节。

抱歉省略了服务器信息。我不确定是否允许我发布它...

任何人都可以给我任何提示,任何我应该阅读的信息的链接,关键字,任何东西。我还有很长的路要走,我确信我应该使用某种类型的抽象,比如 Express,但你必须从某个地方开始。

最佳答案

想通了。答案是here

我没有正确使用Content-Disposition。它并不是一个 header ,而是消息正文的一部分(这解释了更大的 Content-Length

正确代码:

    var boundary = '------------------------69b2c2b9c464731d'


var body = `--${boundary}
\nContent-Disposition: form-data; name="image"

\nContent-type: plain/text
\nimage=${img}
\n${boundary}--`;

postOptions = {

headers: {
'Content-Type': 'multipart/form-data; boundary='+boundary ,
'Content-Length': Buffer.byteLength(body)
} ,

host: 'xxx.yyyyyyyyyy.com' ,
port: '8082' ,
path: '/server/post.php' ,
method: 'POST'
} ;

// Set up the request
post_req = http.request(
postOptions,
function(res) {
//
res.setEncoding('utf8') ;

res.on('data', function (chunk) {
console.log('Response: ' + chunk) ;
}) ;

}) ;

// post the data
post_req.write(body) ;
post_req.end() ;

关于node.js - 内容类型为 : multipart/form-data Troubleshooting 的 NodeJS Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45149563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com