无法使用React发送有效的请求(正在使用curl)

2024-09-23 22:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试连接到使用aiohttp制作的小型服务器。这是一个post请求,下面是使用HTTPie时的情况(它也可以与curl一起使用):HTTPIE screenshot 下面是我用react试过的:

    const requestOptions = {
      method: 'POST',
      body: encodeURIComponent('username=thomas&password=yolo'),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      }
    };
    fetch("http://localhost:8080/login", requestOptions)
        .then(response => response.json())
        .then(data => console.log("data:" + data))

但是这个请求不起作用:我在服务器端得到了这个错误:“需要用户名和密码字段”(服务器主文件src:https://hasteb.in/amucojas.py)。 这是我的浏览器的屏幕:browser

正如您在这个屏幕显示中所看到的,发送的请求最后包含一个“:”。你认为这可能是问题所在吗?我做错什么了吗?在哪一边

编辑:还尝试使用以下选项发送相同的请求:

    const requestOptions = {
      method: 'POST',
      body: JSON.stringify({ "username" : "thomas", "password" : "yolo"}),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    };

它在浏览器中看起来更好一些,但服务器返回相同的错误。 下面是curl-v的结果: curl -v


Tags: 服务器jsondataapplicationusernamethomasyolobody
2条回答

这是我在这个网站上找到的第一个解决方案。这可能不是最好的一个,因为它是为react native设计的,但这是目前最适合我的:

    var details = {
      'username': 'thomas',
      'password': 'yolo'
    };

    var formBody = [];
    for (var property in details) {
      var encodedKey = encodeURIComponent(property);
      var encodedValue = encodeURIComponent(details[property]);
      formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    fetch('http://localhost:8080/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      body: formBody
    })
      .then(response => response.json())
      .then(response => console.log(response));

我尝试使用URLSearchParams,但没有成功

试一试

const user = {
    username: 'thomas',
    password: 'yolo'
};

const requestOptions = {
    method: 'POST',
    body: JSON.stringify(user),
    headers: {
        'Content-Type': 'application/json'
    }
}

fetch('http://localhost:8080/login', requestOptions)
    .then(response => response.json())
    .then(response => console.log(response));

相关问题 更多 >