首页 > 解决方案 > 设置 XHR 请求标头在 Node js 中运行后端两次

问题描述

这是我前面的 Ajax 代码

let ii = 0
function dothisone(e) {


  e.preventDefault();

  ii++

  var xhr = new XMLHttpRequest();
  xhr.withCredentials = true;

  xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
      console.log( this.responseText);
      console.log('Ajax ran: ', ii, 'Times');
    }
  });

  xhr.open("POST", "http://localhost:3000/api/");
  xhr.setRequestHeader("Content-Type", "application/json");


  xhr.send();

  console.log('You hit the button: ', ii, 'Times');
}

这是我在节点 js 中的后端代码

var http = require('http');
var url = require('url');

let numt = 0;

http.createServer(function (req, res) {

numt++;
   
  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',

    'Access-Control-Allow-Headers': 'content-type, Accept, Authorization',

    'Access-Control-Allow-Credentials': false,

  });
  var q = url.parse(req.url, true);
  var txt = q.year + " " + q.month;
  console.log('Backend got',numt,'hit(s)');

  res.end(txt);
}).listen(9000);

每个请求/按钮的 console.log 在我的后端点击两次并显示

// first request
Backend got 1 hit(s)                                                                                                                                        
Backend got 2 hit(s)
// another request
Backend got 3 hit(s)                                                                                                                                        
Backend got 4 hit(s)

这只发生在我在 xhr 请求中设置此(或发送前的任何其他标头)时

xhr.setRequestHeader("Content-Type", "application/json");

请帮忙!!!我正在使用纯节点js。请不要框架。谢谢

标签: javascriptnode.jsajaxxmlhttprequest

解决方案


推荐阅读