javascript - 设置 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。请不要框架。谢谢
解决方案
推荐阅读
- reactjs - 如何使用 React Typescript 使用 Portal 创建模态(对话框)
- python-3.x - Pygsheets 和 AWS Lamba
- python - Django中的外键POST
- javascript - 使用 yarn start 或 npm start 无法在浏览器中打开 React 应用程序
- c++ - 检查哪个对象调用了对方的对象方法
- apache-flink - Kinesis Streams 和 Flink
- python - 如何以所有可能的组合在多个文件之间获取公共行/列 - python/pandas
- java - 数组排序 NullpointerException
- zebra-printers - ZPL 批量打印船标签问题...内存限制?
- windows - 如何使用 PowerShell(UTF-8 文件名)扩展 ZIP 存档