简体   繁体   English

尝试使用 python 和 JSON object 发送 POST 请求并将响应打印到 CSV 文件中

[英]trying to send a POST request using python with a JSON object and print the response into a CSV file

I am trying to send a post request using python script and want to store the response.我正在尝试使用 python 脚本发送发布请求并希望存储响应。 Below are the two file.下面是两个文件。 Everything is fine when i do the same thing using node.js but when I use a python script instead of node.js it give me this error.当我使用 node.js 做同样的事情时,一切都很好,但是当我使用 python 脚本而不是 node.js 时,它给了我这个错误。 Any one know why?有谁知道为什么? not able to find the proper reason why this error pop up.无法找到弹出此错误的正确原因。

in request sending first name and last name and in response i will get the full name在发送名字和姓氏的请求中,作为回应,我将获得全名

Node.js Code (used fastify) Node.js 代码(使用 fastify)

 const conn=require('fastify')({ logger:true }) const PORT=80 const axios = require('axios') //take first and last name as request and in response return full name conn.post('/user',async(req,res)=>{ const user=req.body const fullname=user.first_name + user.last_name console.log(full) res.json(fullname) }) const start_server=async()=>{ try { await conn.listen(PORT) console.log(`server start at PORT ${PORT}`) } catch(error) { conn.log.error(error) process.exit(1) } } start_server()

my Python script我的 Python 脚本

 import requests import json API_ENDPOINT = 'http://localhost:80/user' headers = {'Content-type': 'application/json'} data = { "first_name": "jayanta", "last_name": "lahkar" } r = requests.post('http://localhost:80/user', data) print(r.json())

Error message错误信息

{'statusCode': 415, 'code': 'FST_ERR_CTP_INVALID_MEDIA_TYPE', 'error': 'Unsupported Media Type', 'message': 'Unsupported Media Type: application/x-www-form-urlencoded'}

Try:尝试:

r = requests.post(url = 'http://localhost:80/user', headers=headers, data=data)

print(r.json())

in the python script:在 python 脚本中:

use json使用json

r = requests.post(url = 'http://localhost:80/user', headers=headers, json=data)

in the node script:在节点脚本中:

use .send method使用.send方法

const {first_name, last_name} =req.body;
const fullname={first_name, last_name};
res.send(fullname);

here is the answer to your error:这是您的错误的答案:

axios.post('url', data, {
        headers: {
            'Content-Type': 'application/json',
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM