LEARNING JAVASCRIPT - Trang 296

const

http

=

require

(

'http'

);

const

server

=

http

.

createServer

(

function

(

req

,

res

) {

res

.

setHeader

(

'Content-Type'

,

'application/json'

);

res

.

setHeader

(

'Access-Control-Allow-Origin'

,

'*'

);

res

.

end

(

JSON

.

stringify

({

platform

:

process

.

platform

,

nodeVersion

:

process

.

version

,

uptime

:

Math

.

round

(

process

.

uptime

()),

}));
});

const

port

=

7070

;

server

.

listen

(

port

,

function

() {

console.log(

`Ajax server started on port

${

port

}

`

);

});

This creates a very simple server that reports the platform (“linux,” “darwin,” “win32,”

etc.), the version of Node.js, and the server uptime.

Ajax introduced the possibility of a security vulnerability called

cross-origin resource sharing (CORS). In this example, we are

adding a header of Access-Control-Allow-Origin with a value of
*

, which signals to the client (the browser) not to prevent the call

for security reasons. On a production server, you would either

want to use the same protocol, domain, and port (which will be

allowed by default), or specify explicitly what protocol, domain,

and port can access the endpoint. For demonstration purposes,

though, it is safe to disable CORS checking like this.

To start this server, simply run:

$ babel-node ajaxServer.js

If you load

http://localhost:7070

in a browser, you will see the output of the server.

Now that we have a server, we can make an Ajax code from our sample HTML page

(you can use the same one that we’ve been using through this chapter). We’ll start by

adding a placeholder somewhere in the body that will receive the information:

<

div

class

=

"serverInfo"

>

Server is running on <

span

data-replace

=

"platform"

>???</

span

>

with Node <

span

data-replace

=

"nodeVersion"

>???</

span

>. It has

been up for <

span

data-replace

=

"uptime"

>???</

span

> seconds.

</

div

>

Now that we have a place to put the data that’s coming from the server, we can use

XMLHttpRequest

to perform an Ajax call. At the bottom of your HTML file (right

before the closing

</body>

tag), add the following script:

272 | Chapter 18: JavaScript in the Browser

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.