ElectronJS:使用net发起http post请求时,后台获取不到数据的问题

Electron官方推荐使用net直接发起http/https请求。
在使用get方式时,java后台很轻松就解析出了传输的数据。
但使用post方式时,后台一直显示为null
多方调查后发现,net和ajax请求方式一样,某些时候不能使用json的数据格式。
以下为正确格式

const {net} = require('electron').remote;
const querystring = require('querystring');
var cache = [];
var postData = querystring.stringify({
    'test' : '111'
});

// 请求体
const request = net.request({
    method: 'POST',
    protocol: 'http:',
    hostname: '127.0.0.1',
    port: 8080,
    path: '/Test',
    headers: {
    	// 这里要将content-type改成这种提交form表单时使用的格式
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        // 标明数据长度
        'Content-Length': postData.length
    }
});

// 回调
request.on('response', (response) => {
    console.log(`**statusCode:${response.statusCode}`);
    // 将response的内容输出出来
    console.log(`**header:${JSON.stringify(response, function(key, value) {
        if (typeof value === 'object' && value !== null) {
            if (cache.indexOf(value) !== -1) {
                // 移除
                return;
            }
            // 收集所有的值
            cache.push(value);
        }
        return value;
    })}`);
    cache = null;
    response.on("data", (chunk) => {
        console.log("接收到数据:", chunk.toString());
    })
    response.on('end', () => {
        console.log("数据接收完成");
    })
});
// 写入数据
request.write(postData);
// 结束请求
request.end();

主要就是把content-type的类型换一下,完美解决。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C#实现HTTP POST请求,设置Header并获取JSON数据并保存到MySQL数据库的示例代码: ```csharp using System; using System.Net; using System.IO; using System.Text; using MySql.Data.MySqlClient; using Newtonsoft.Json; namespace HttpPostExample { class Program { static void Main(string[] args) { // 设置POST请求的URL地址 string url = "https://example.com/api/data"; // 设置POST请求的Header WebRequest request = WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; request.Headers["Authorization"] = "Bearer your_access_token_here"; // 构造POST请求JSON数据 string postData = JsonConvert.SerializeObject(new { name = "John", age = 30 }); // 将JSON数据写入请求流中 byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); // 发送POST请求获取响应 WebResponse response = request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); // 关闭流 reader.Close(); dataStream.Close(); response.Close(); // 解析JSON数据并保存到MySQL数据库 dynamic data = JsonConvert.DeserializeObject(responseFromServer); string connectionString = "server=localhost;database=mydatabase;uid=myusername;password=mypassword;"; using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); MySqlCommand command = connection.CreateCommand(); command.CommandText = "INSERT INTO mytable (name, age) VALUES (@name, @age)"; command.Parameters.AddWithValue("@name", data.name); command.Parameters.AddWithValue("@age", data.age); command.ExecuteNonQuery(); connection.Close(); } Console.WriteLine("Data saved to database successfully."); } } } ``` 在上面的示例代码中,我们首先设置POST请求的URL地址和Header,然后构造POST请求JSON数据并将其写入请求流中。接下来,我们发送POST请求获取响应,并将响应的JSON数据解析并保存到MySQL数据库中。最后,我们输出一条消息表示数据已成功保存到数据库中。 请注意,示例代码中使用Json.NET库来处理JSON数据。如果您没有安装此库,请使用NuGet包管理器安装它。您还需要将MySQL.Data.dll添加到您的项目引用中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值