对本地nodejs服务器的简单ajax请求

编程入门 行业动态 更新时间:2024-10-26 02:37:05
本文介绍了对本地nodejs服务器的简单ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我写了一个非常简单的服务器:

I wrote very simple server :

/* Creating server */ var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.end("Hello World\n"); }); /*Start listening*/ server.listen(8000);

我使用nodejs运行它.

I run it using nodejs.

现在,我想编写一个简单的客户端,该客户端使用ajax调用将请求发送到服务器并打印响应(Hello World)

Now i want to write simple client that use ajax call to send request to server and print response (Hello World)

以下是clinet的javascript:

Here javascript of clinet:

$.ajax({ type: "GET", url: "127.0.0.1:8000/" , success: function (data) { console.log(data.toString); } });

当我打开客户端html文件时,在控制台中出现以下错误:

When I open client html file i get following error in console:

XMLHttpRequest cannot load 127.0.0.1:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我尝试将以下内容添加到ajax调用中:

I tried adding to ajax call following:

$.ajax({ type: "GET", url: "127.0.0.1:8000/" , dataType: 'jsonp', crossDomain: true, success: function (data) { console.log(data.toString); } });

但是我得到

Resource interpreted as Script but transferred with MIME type text/plain: "127.0.0.1:8000/?callback=jQuery211046317202714271843_1410340033163&_=1410340033164".

任何人都可以解释我做错了什么,也许怎么解决?

Anyone can explain what i did wrong and perhaps how to fix it?

非常感谢!

推荐答案

第一个错误是由 CORS (跨来源资源共享)政策.所有浏览器都规定,除了向远程服务器允许通过Access-Control-Allow-Origin标头允许的脚本/页面外,您不能向AJAX中的远程服务器提出请求,而是向当前服务器加载脚本/页面.

The first error is caused by CORS (Cross Origin Resource Sharing) policy. It's rule by all browsers that you cannot make a request to a remote server in AJAX other than to the current server the script/page was loaded from unless that remote server allows it via Access-Control-Allow-Origin header.

我建议从同一Node.js服务器提供页面.然后它将起作用.例如,当请求到达根/页时,然后提供index.html文件,否则,服务器处理您想要的任何其他内容.

I suggest serving the page from the same Node.js server. Then it will work. Example, when the request comes to root / page, then serve the index.html file, otherwise, server whatever other content you want.

var http = require('http'), fs = require('fs'); /* Creating server */ var server = http.createServer(function (request, response) { if (request.url == '/' || request.url == '/index.html') { var fileStream = fs.createReadStream('./index.html'); fileStream.pipe(response); } else { response.writeHead(200, {"Content-Type": "text/plain"}); response.end("Hello World\n"); } }); /*Start listening*/ server.listen(8000);

更多推荐

对本地nodejs服务器的简单ajax请求

本文发布于:2023-10-30 03:33:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541644.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简单   服务器   nodejs   ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!