簡體   English   中英

Node Express使用python API POST時的空體(請求庫)

[英]Node Express Empty body when using python API POST (requests library)

我正在使用@ErikRas的入門套件

使用以下代碼,我無法驗證我的python程序。

這是我的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為空,Python Post Request Body在節點服務器中顯示為空

但如您所見,我已經在使用bodyparser.json和bodyparser.urlencoded.extended = true

好的,所以我通過將請求打印到節點中的控制台,將pythons請求與Web應用程序的請求進行了比較。

我發現Web應用程序的標題比python的請求請求更多。 Web應用程序:引薦: ' HTTP://本地主機:3001 /登錄 '產地: ' HTTP://本地主機:3001 '主持人: ' HTTP://本地主機:3001 '連接: '關閉'

所以我將其包含在標題中, 它起作用了!

我想看看哪個標頭屬性是“必需的”,所以我逐漸將所有內容拉出,以查看是否破壞了POST請求。

原來我設法把一切都拉出來了! 所以我現在使用的是:

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

而已!! 我想了解為什么headers = {}有效,但我需要繼續我的項目!

<<<<<< ----編輯---- >>>>>>

上面是“一半”的權利,因為我的Web應用程序正在使用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體解析器。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM