NodeJ在收到POST请求后以JSON响应python

时间:2019-06-11 07:17:24

标签: javascript python node.js json express

无法弄清楚在接收到来自python的发布请求后如何使用Node服务器到python的JSON数据进行响应。

节点js

const express = require("express");
const bodyParser = require("body-parser");
const request = require('request');
const app = express();

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

app.post("/postdata",(req,res)=>{
    res.setHeader('Content-Type', 'application/json');
    var a = req.body.name;
    var b = req.body.job;
    console.log(a);
    console.log(b);

    var json={
        "name":"Bobby",
        "job":"Cook"
    } 

    res.json(JSON.stringify(json));

})
app.listen(3000);

Python

import requests
import json

url='http://localhost:3000/postdata'
headers = {"content-type":"application/json"}

requests.post(url,
    json={
        "name":"Edward",
        "job":"Teacher"
    })

data = requests.get(url,headers=headers).json()

print(data)

运行python脚本后,我确实在节点服务器控制台中得到了教师Edward的结果。 但是从python我得到了错误:

Traceback (most recent call last):
  File "pClient.py", line 13, in <module>
    data = requests.get(url,headers=headers).json()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

0 个答案:

没有答案
相关问题