简体   繁体   English

如何使用 AXIOS 使用 object 向我的 NodeJS 服务器发送 POST 请求?

[英]How to send a POST request to my NodeJS server with an object using AXIOS?

Everything works as intended using POSTMAN.使用 POSTMAN,一切都按预期工作。 but from my application, I don't get the same results, or no results to be precise.但是从我的应用程序中,我没有得到相同的结果,或者没有准确的结果。

Here is my React code:这是我的反应代码:

const jsonObj = JSON.stringify({ email, subject, body })

const config = {
    headers: {
        'Content-Type': 'application/JSON',                
    }
}

try {            
    const response = await axios.post('http://localhost:5000', jsonObj, config); 
                    
    console.log(response);
} catch (e) {            
    console.log(e);
}

And this is my NodeJS code:这是我的 NodeJS 代码:

import http from 'http';

function response(res, statusCode, contentType, message) {  
    res.writeHead(statusCode, { "Content-Type": contentType, "Access-Control-Allow-Origin": "http://<SERVER_NAME>:<PORT>" });
    res.end(JSON.stringify({ message }));
}

const server = http.createServer((req, res) => {
    if (req.url === '/' && req.method === 'POST') {
        try {
            let body = '';

            req.on('data', (chunk) => {
                body += chunk.toString();

            });

            req.on('end', () => console.log(JSON.parse(body)));
            response(res, 201, 'application/json', 'Email was successfully sent...');
        } catch(e) {
            response(res, 500, 'application/json', e);
        }
    }
})

server.listen(<PORT>, () => console.log('Server listening...'));

I tried AXIOS post requests using text/plain and application/x-www-form-urlencoded .我使用text/plainapplication/x-www-form-urlencoded尝试了 AXIOS 发布请求。 Both works as intended, but I need to post the data as JSON.两者都按预期工作,但我需要将数据发布为 JSON。 When I remove the headers object from AXIOS, it works, but this is because the default header is application/x-www-form-urlencoded .当我从 AXIOS 中删除标题 object 时,它可以工作,但这是因为默认 header 是application/x-www-form-urlencoded

So my question is: How do I post an object with AXIOS as JSON?所以我的问题是:如何发布 object 和 AXIOS 作为 JSON? because it is automatically serialized as JSON according to what I've read!因为根据我的阅读,它会自动序列化为 JSON !

EDIT:编辑:

Apparently the problem is not exclusive to AXIOS, I tried the same thing with FETCH API and the problem persists, the code won't work if I set Content-Type to application/json显然这个问题不是 AXIOS 独有的,我用 FETCH API 尝试了同样的事情,问题仍然存在,如果我将Content-Type设置为application/json ,代码将不起作用

EDIT 2:编辑2:

It works normally in cURL as well as POSTMAN.它在 cURL 和 POSTMAN 中正常工作。 The problem is still with my application.问题仍然存在于我的应用程序中。

I tried fetching data from jsonplaceholder.typicode and it works.我尝试从 jsonplaceholder.typicode 获取数据并且它有效。 So maybe the problem is with NodeJS, but again it worked with everything except my client side code.所以也许问题出在 NodeJS 上,但它再次适用于除了我的客户端代码之外的所有内容。 Absolutely no idea what is going on.完全不知道发生了什么。

EDIT 3:编辑 3:

It worked after converting my server file from raw NodeJS to express, and it worked.在将我的服务器文件从原始 NodeJS 转换为 express 之后,它起作用了,并且它起作用了。 So maybe the problem is with parsing JSON data.所以也许问题在于解析 JSON 数据。

For axios we don't need to stringify the javascript object.对于 axios,我们不需要对 javascript object 进行字符串化。

const jsonObj = { email, subject, body };

const config = {
    headers: {
        'Content-Type': 'application/JSON',                
    }
}

try {            
    const response = await axios.post('http://localhost:5000', jsonObj, config); 
                    
    console.log(response);
} catch (e) {            
    console.log(e);
}

Try node js code some thing like this:尝试 node js 代码,如下所示:

function getPostData(req) {
    return new Promise((resolve, reject) => {
        try {
            let body = ''
            req.on('data', (chunk) => {
                body += chunk.toString()
            })
            req.on('end', () => {
                resolve(body)
            })

        } catch (error) {
            reject(err)
        }
    })
}
const body = await getPostData(req);
const { email, subject, body} = JSON.parse(body)
        const product = {
            email,
            subject,
            body
        }

        res.writeHead(201, { 'Content-Type': 'application/json' })
        return res.end(JSON.stringify(product))

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

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