首页 > 解决方案 > 将 Content-Type 设置为 json 但请求以 x-www-form-urlencoded 形式出现

问题描述

我正在使用 ajax 将帖子发送到我的应用程序。在邮递员中,一切都按预期工作,但是在浏览器中,数据进来了x-www-form-urlencoded,数据丢失了。

下面是我的 ajax 和 postman 配置以及它们在 req 中的相应标题...

$.ajax({
        url: '/',
        headers: {
            'Accept': 'application/json',
            'Content-Type': "application/json"
        }, // send as JSON
        data: JSON.stringify(formData),
        method: 'POST'

    });


 headers:
      { host: 'localhost:8080',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0',
        accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'accept-language': 'en-US,en;q=0.5',
        'accept-encoding': 'gzip, deflate',
        referer: 'http://localhost:8080/',
        'content-type': 'application/x-www-form-urlencoded',
        'content-length': '0',
        connection: 'keep-alive',
        'upgrade-insecure-requests': '1',
        pragma: 'no-cache',
        'cache-control': 'no-cache' }

在此处输入图像描述

 headers:
      { data: '{"name":"tester", "email": "t@t.com", "message":"This is a test"}',
        contenttype: 'application/json',
        datatype: 'xml/html/script/json',
        'cache-control': 'no-cache',
        'postman-token': 'cbaa5cbe-0ab8-4328-abfd-f5dc6a6acd90',
        'user-agent': 'PostmanRuntime/7.1.1',
        accept: '*/*',
        host: 'localhost:8080',
        'accept-encoding': 'gzip, deflate',
        'content-length': '0',
        connection: 'keep-alive' }

还有我的相关服务器代码:

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

app.post('/', function (req, res) {
    console.log(res);
    console.log('----------------------------------------------------------');
    console.log(req);
    //var jsonData = JSON.parse(req.headers.data);
    console.log(req.body);
    console.log(req.data);
    let transporter = courier.createTransport({...});
    let mailOptions = {...};
    transporter.sendMail(mailOptions, function (error, info) {
        if (error)
            console.log(error);
        else
            console.log('email sent:' + info.response);
    });
    res.render('index', {
        title: 'Projects',
        projects: projects
    });
});


app.get('/', function (req, res) {
    res.render('index', {
        title: 'Projects',
        projects: projects
    });
});

请停下!

标签: node.jsajaxpost

解决方案


你可以简单地:
JSON.parse(data)
在你
success: function(data){
var object =JSON.parse(data);
}
的 json 解析数据后,你可以做任何你喜欢的事情。


推荐阅读