[英]Cant do a Post request with Axios to NestJS endpoint
I got a react Component that does a post request to an NestJS endpoint and for some reason i cant provide a body.我有一个反应组件,它向 NestJS 端点发出发布请求,但由于某种原因我无法提供主体。 Every time i attach an object to the body i will get an error in the console saying "Error: Network Error".
每次我将一个对象附加到主体时,我都会在控制台中收到一条错误消息:“错误:网络错误”。
If i just provide a string in my axios post i will get a response from the NestJs server.如果我只是在我的 axios 帖子中提供一个字符串,我将收到来自 NestJs 服务器的响应。
And everything works fine if i try it with Postman.如果我与 Postman 一起尝试,一切正常。
Request in React:在反应中请求:
const getImage = async () => {
try {
const result = await Axios.post('http://localhost:8081/abstract/image', {test: 'asd'} )
} catch (e) {
console.log(e)
}
}
NestJS Controller: NestJS 控制器:
@Post('image')
@Header('Content-Type', 'image/png')
@Header('Access-Control-Allow-Origin', '*')
@Header("Access-Control-Allow-Credentials", "true")
@Header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT')
@Header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers")
async getImageBuffer(
@Body() completeBody
) {
console.log(completeBody)
}
If you are using create-react-app to build your react app, consider adding proxy
to your package.json file like this:如果您使用 create-react-app 来构建您的 React 应用程序,请考虑将
proxy
添加到您的 package.json 文件中,如下所示:
{
"name": "your-awesome-app",
"version": "whatever-version-it-is",
"proxy": "http://localhost:8081"
"dependencies": {... all your dependencies}
"devDependencies": {... all your devDependencies}
}
And change your code like this:并像这样更改您的代码:
const getImage = async () => {
try {
const result = await
Axios.post('abstract/image', {test: 'asd'} )
} catch (e) {
console.log(e)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.