ajax nodejs 前后端发送接收消息并回应

刚刚接触nodejs ,最近想实现前后端的通信,不知道为啥实现不了。代码如下
ajax:
var sending = function() {

    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("show").innerHTML = xmlhttp.responseText;
        } else {
            document.getElementById("show").innerHTML = xmlhttp.readyState;
            document.getElementById("show").innerHTML += '  ' + xmlhttp.status;
        }
    }
    xmlhttp.open("PSOT", "127.0.0.1", true);
    xmlhttp.send("lalal");
    
    

nodejs:
var http = require("http");
var querystring = require("querystring");
http.createServer(function(req, res) {

res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('hello world');

}).listen(8080, '127.0.0.1');
console.log("running");

求教大神为何实现不了啊?另外这是chrome显示的错误信息
Uncaught DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL

阅读 4.5k
5 个回答

解决方案:
前端部分 xmlhttp.open("POST", "http://localhost:8080/", true);
后端部分 var http = require("http");

http.createServer(function(req, res) {

res.writeHeader(200, {
    **'content-type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Request-Method': 'POST,GET,OPTIONS',
    'Access-Control-Request-Headers': 'content-type'**
});

res.end('hello world');

}).listen(8080, '127.0.0.1');

console.log("running");
亲测有效

Ajax请求的时候没加8080端口

提示已经很明显了,url要么写绝对地址,要么相对地址(同一站点的情况下),你写的127.0.0.1什么也不是。

新手上路,请多包涵

传递的URL形式错了,你传的只是ip地址部分,而且我看你后台也没有配置路由规则

POST都写错了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题