【问题标题】:Node Express Empty body when using python API POST (requests library)使用 python API POST(请求库)时的 Node Express 空正文
【发布时间】:2019-09-08 00:14:44
【问题描述】:

我正在使用@ErikRas 的入门工具包

使用以下代码,我无法验证我的 python 程序。

这是我的蟒蛇:

import requests
URL="http://localhost"
PORT="3030"

Session = requests.Session()
Request = Session.post(URL+':'+PORT+'/login', data={'name':'AuthedUserName'})
# (Password to follow proof of concept obviously)

在我刚刚拥有的 api.js 文件中:

import express from 'express';
import session from 'express-session';
import bodyParser from 'body-parser';
import config from '../src/config';
import * as actions from './actions/index';
import {mapUrl} from 'utils/url.js';
import http from 'http';

const app = express();

const server = new http.Server(app);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
  secret: 'react and redux rule!!!!',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 60000 }
}));

app.use((req, res) => {
/* There's heaps here, but all that is relevant is: */
console.log(req.body)

在控制台中我刚刚得到{}

我找到了这篇文章: req.body empty on postsPython Post Request Body appears empty in Node server when sent

但正如你所见,我已经在使用 bodyparser.json 和 bodyparser.urlencoded.extended = true

【问题讨论】:

  • 您是否从 Python 端获得 200?在帖子行后输入Request.raise_for_status()
  • 我得到了 404,但那是因为 node 得到了 req.body.user == 'undefined' ,所以验证是平淡的。但是现在我有了 headers={},我得到了 200

标签: python node.js rest express


【解决方案1】:

好的,所以我通过将请求打印到节点中的控制台来比较我的 python 请求和我的网络应用程序的请求。

我发现 Web 应用程序的标头中包含的内容比 python 的请求更多。网络应用程序: 推荐人:'http://localhost:3001/login' 来源:'http://localhost:3001' 主持人:'http://localhost:3001' 连接:'关闭'

所以我将它包含在我的标题中,成功了!

我想看看哪个标头属性是“必要的”,所以我逐渐把所有东西都拿出来看看这是否破坏了 POST 请求。

原来我设法把所有东西都拿出来了!所以我现在使用的是这个:

r = Session.post(URL+':'+PORT+'/login',headers = {}, data={'name':'AuthedUserName'})

就是这样!!我想了解为什么 headers={} 有效,但我需要继续我的项目!!

>>>>>

上面是“一半”,因为我的网络应用程序使用的是 json,而我想使用 json,我需要做的就是将我的标题更改为

headers = {u'content-type': u'application/json'}

然后仅在有效负载上使用 json.dumps!

r = session.post('http://'+DB_URL+':3030/sinumecUpdate', headers = headers, data = json.dumps(dataObject))

我也需要退出

app.use(bodyParser.urlencoded({ extended: true }));

从我的节点 API 并坚持只使用 JSON 正文解析器。

【讨论】:

    【解决方案2】:
    import requests
    import json
    
    url = 'http://127.0.0.1'
    data={'name':'AuthedUserName'}
    headers = {'content-type': 'application/json'}
    
    r = requests.post(url=url, data=json.dumps(data), headers=headers)
    

    【讨论】:

    猜你喜欢
    • 2019-06-26
    • 1970-01-01
    • 2017-11-17
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 2018-01-14
    • 1970-01-01
    相关资源
    最近更新 更多