【问题标题】:Why im not receiving the data in nodejs server using xmlhttprequest "POST"?为什么我没有使用 xmlhttprequest "POST" 在 nodejs 服务器中接收数据?
【发布时间】:2019-09-05 08:16:10
【问题描述】:

我使用 XMLHttpRequest "POST" 从 ajax.js 向后端 server.js 发送数据,一切正常,除了收到的是 UNDEFINED ,当我使用 "console.log" 时使用 "req.body" im期待看到它像 "{name: 'MrSalsa'}" ,但不幸的是它的打印是这样的 "[Object: null prototype] { MrSalsa: '' }"

这是前端的 ajax.js:

document.getElementById('btnPost').addEventListener('click', 
function(e){
  e.preventDefault();
  var data = document.getElementById('input').value;

  var xhr = new XMLHttpRequest();
  xhr.open('post', '/api', true);
  xhr.setRequestHeader('Content-type', 'application/x-www-form- 
urlencoded');
  xhr.onload = function(){
    if(this.status == 200){
      document.getElementById('text').innerText = this.responseText;
    }else if(this.status == 403){
      document.getElementById('text').innerText = this.responseText;
    }else if(this.status == 404){
      document.getElementById('text').innerText = this.responseText;
 }
 }
  xhr.send(data);
})

这是后端 server.js 文件:

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
const PORT = process.env.PORT || 5050;

var users = require('./views/resources/users')

app.use(express.static(path.join(__dirname, 'views')));

app.set('view engine', 'ejs');

app.get('/', (req,res)=>{
  res.render('home');
})
app.get('/api', (req,res)=>{
  res.json(users);
})
//the problem is bellow in the "POST" handler
app.post('/api', urlencodedParser, (req,res)=>{
   console.log(req.body);
res.send('welcome '+req.body.name);
})

app.listen(PORT, console.log(`Server running on PORT : ${PORT}`));

这是 HTML 文件中的表单:

<form>
  <input id="input" type="text" name="name" placeholder="text 
  here.." required>
  <button id="btnPost" type="submit">Post</button>
</form>

当我 console.log 它是结果:

[nodemon] starting `node server.js`
Server running on PORT : 5050
[Object: null prototype] { MrSalsa: '' }

我试着像这样在前端制作一个对象:

xhr.send({name: data});

但是当我 console.log 它是结果:

[nodemon] starting `node server.js`
Server running on PORT : 5050
[Object: null prototype] { '[object Object]': '' }

我是否错过了理解/错过了什么? Ty寻求帮助:)

【问题讨论】:

  • 由于服务器需要表单数据,您应该发送FormData ...例如xhr.send(new FormData(form)) - 其中form 是您的表单...
  • xhr.send(new FormData(this.form)) 可能适用于您的代码
  • 试一试,这就是我得到的
  • [nodemon] starting node server.js` 服务器在 PORT 上运行:5050 [对象:空原型] { '------WebKitFormBoundaryMEaPRIXLKCdBU4Z6\r\nContent-Disposition: form-data; name': '"name"\r\n\r\nMr_Salsa\r\n------WebKitFormBoundaryMEaPRIXLKCdBU4Z6--\r\n' } `

标签: javascript node.js post xmlhttprequest


【解决方案1】:

就像之前的 cmets 所说,您将内容类型设置为 x-www-form- urlencoded,因此您应该将数据作为 FormData 传递。如果我是你,我会简单地将内容类型更改为application/json。这应该可以解决您的问题

【讨论】:

  • 不适用于application/jsonx-form-urlecoded
  • 这就是我现在得到的 [nodemon] starting node server.js` 服务器在 PORT 上运行:5050 [对象:空原型] { '------WebKitFormBoundaryMEaPRIXLKCdBU4Z6\r\nContent-Disposition:表格数据; name': '"name"\r\n\r\nMr_Salsa\r\n------WebKitFormBoundaryMEaPRIXLKCdBU4Z6--\r\n' } `
  • If I were you, I would simply change the content type to application/json - 这也需要更改 server 代码
  • 我使用了application/json 并在 server.js 文件中添加了这个app.use(bodyParser.json()) 修复了问题谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-11-30
  • 2020-04-13
  • 2015-05-07
  • 1970-01-01
  • 2019-08-27
  • 2020-12-09
  • 2017-08-23
  • 2019-06-13
相关资源
最近更新 更多