【问题标题】:expressjs http post not able to get data from javascript post fetchexpressjs http post 无法从 javascript post fetch 获取数据
【发布时间】:2020-09-11 04:54:27
【问题描述】:

尝试从 http 帖子中 console.log 节点脚本中的数据

const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));

const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static('public'));

app.post('/do-login', function(req, res) {
    console.log( req.body );
});

在客户端,我使用 javascript fetch 将数据发送到节点后端

let data = {
    email :'test@domain.com',
    password : 'test'
}

fetch('http://localhost:3700/do-login',{
    method : 'post',
    body : JSON.stringify(data)
}).then(function(response) {
    return response.json();
}).then(function(data) {
    console.log(data);
});

但不走运,它返回一个空对象

但是,如果我使用帖子xmlHttpRequest

var http = new XMLHttpRequest();
var url = 'http://localhost:3700/do-login';
var params = 'email=test@domain.com&password=test';
http.open('POST', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

我能够接收到客户端发送的数据。有什么问题?

非常感谢任何帮助和想法。

【问题讨论】:

  • 您的 fetch 正在发送 JSON ...您的 XHR 正在发送 application/x-www-form-urlencoded ... 这两段代码没有可比性
  • 解决方案 1) 在使用 fetch 时发送 x-www-form-urlencoded 数据,或 2) 在 fetch 请求中将 content-type 设置为 application/json
  • @JaromandaX 我愿意接受你的回答,请发表。
  • 别人的回答也一样好 - 我不会回答

标签: javascript node.js express fetch


【解决方案1】:

以 form-url-encoded 格式发送请求。首先,创建一个处理formUrlEncoding的方法。

formUrlEncoder(params, formUrlBody){
    
    for (let property in params) {
      let key = encodeURIComponent(property);
      let value = encodeURIComponent(params[property]);
      formUrlBody.push(key + "=" + value);
    }
    return formUrlBody.join("&");
}

接下来,调用将返回所有编码值的方法,只需将其传递到正文中即可。

const url = 'http://localhost:3700/do-login';
const params = {
  email :'test@domain.com',
  password : 'test'
};
const headers = new Headers({
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});

let formUrlBody = [];
formUrlBody = formUrlEncoder(params, formUrlBody);

fetch(url, {
  method: 'POST',
  headers: headers,
  body: formUrlBody
});

您可以找到有关 fetch here 的更多详细信息。

【讨论】:

猜你喜欢
  • 2015-07-08
  • 1970-01-01
  • 2016-03-19
  • 2017-06-16
  • 2015-10-22
  • 1970-01-01
  • 2020-07-19
  • 2022-01-08
  • 1970-01-01
相关资源
最近更新 更多