【问题标题】:HTTP empty stringHTTP 空字符串
【发布时间】:2021-03-21 22:58:40
【问题描述】:

我正在编写一个简单的脚本来将 URL 发送到快速服务器。当我想 console.log req.body 时,我得到一个空字符串,即使我使用了解析器。你能帮我解决这个问题吗?

客户

document.addEventListener('keypress', logKey);

const API_URL = 'http://localhost:8000/bilder';

var image = document.getElementsByTagName('img')[0].src;

function logKey(e) {
const Http = new XMLHttpRequest();

Http.open("POST", API_URL);
Http.setRequestHeader('Content-Type', 'application/json');
Http.send(JSON.stringify(image));

Http.onreadystatechange = (e) => {
console.log(Http.responseText)
}
}

服务器

const express = require('express')
const app = express();
var cors = require('cors')
const port = 8000;


app.use(cors());

app.use(express.json());


app.post('/bilder', (req, res) => {
    console.log(req.body)
    res.send("hello world")
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}!`)
});

【问题讨论】:

  • 请问,这里用的Java在哪里?
  • 在发送到服务器之前确认image 不是空字符串吗?
  • 您在字符串上调用JSON.stringify 是否有原因?如果您传递的只是一个字符串值,则无需使用 JSON。 JSON 非常适合结构化数据,但您可以将 text/plain 用于纯文本...
  • xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');没有这个,你就没有身体
  • 我都试过了,但我仍然在服务器控制台上得到一个空字符串。是的,我可以在客户端的控制台中打印图像

标签: javascript express http


【解决方案1】:

我明白了。问题出在帖子的标题和服务器上的解析器中。我必须将xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 添加到客户端的帖子中,而在后端我必须使用app.use(express.urlencoded()); 作为解析器。使用简单的 express 效率不高。所以我了解到,标头需要与后端解析器相同的内容类型。

非常感谢大家和最好的问候

【讨论】:

    猜你喜欢
    • 2015-09-04
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2017-06-12
    • 2023-03-12
    相关资源
    最近更新 更多