将Content-Type设置为json,但请求以x-www-form-urlencoded形式出现

时间:2018-05-05 08:28:53

标签: node.js ajax post

我正在使用ajax将帖子发送到我的应用。在邮递员中,一切都按预期工作,但在浏览器中,数据以x-www-form-urlencoded的形式出现,数据丢失。

以下是我的ajax和邮递员配置及其相应的标题...

$.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' }

enter image description here

 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
    });
});

plz halp!

1 个答案:

答案 0 :(得分:0)

你可以简单地说:
JSON.parse(data)
在你的内心 success: function(data){
var object =JSON.parse(data);
}
一旦json解析数据,你可以随心所欲地做。