尝试使用python发送带有JSON对象的POST请求,并将响应打印到CSV文件中



我正在尝试使用python脚本发送post请求,并希望存储响应。下面是两个文件。当我使用node.js做同样的事情时,一切都很好,但当我使用python脚本而不是node.js时,它会给我这个错误。有人知道为什么吗?无法找到弹出错误的正确原因。

在请求中发送名字和姓氏,而在响应中我将获得全名

Node.js代码(使用快捷)

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

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())

错误消息

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

尝试:

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

在python脚本:

使用json

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

:

使用.send方法

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

下面是你的错误的答案:

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

最新更新