How to write a text in a file in order to make a chat?

-1

My code is:

<meta charset="UTF-8">
<style>body{width=100%;height=100%,margin=0,background-color=black,color=white}</style>
<script>
    xhr=new XMLHttpRequest()
    name=prompt("Enter your nickname please.")
    new File([name+" has connected."],"chat4.js")
    xhr.open("GET","http://nordostein.esy.es/chat4.js")
    xhr.send()
    setInterval(function(){
        eval(xhr.responseText)
        xhr.open("POST","http://nordostein.esy.es/chat4.js")
        xhr.send()
    },1)
    onkeydown=function(e){
        new File([name+" says "+prompt("Enter your message.")],"chat4.js")
    }
</script>

And the error:

  

XMLHttpRequest can not load link ? No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' link ' is therefore not allowed access.

    
asked by P. Flanderson 02.11.2016 в 12:23
source

2 answers

3

What you are seeing is a CORS error . Which means that the browser blocks any call of type XMLHttpRequest that you do outside your domain , to prevent access to private information.

The best solution would be to set up a server to be able to make your app online.

If you want to use Javascript to program the server check out NodeJS that allows you to run Javascript on the server, and here is a tutorial to believe the chat service using SocketIO.

    
answered by 02.11.2016 в 12:58
2

In addition to the response of César Alberca, there is a way to avoid the error of CORS, understanding that when you make an HTTP request to an endpoint with a different domain to the origin domain of the request, a request is made first type OPTIONS , which could be answered by the server with a 2XX status and obligatorily adding the following headers to the answer

"Access-Control-Allow-Origin": "*" //especificas que permites peticiones desde cualquier dominio, el patrón asterisco puede cambiar para restringir desde donde si admites peticiones
"Access-Control-Allow-Headers":"Content-Type,Authorization" //en esta cabecera puedes especificar la lista de cabeceras estándar que admites en las peticiones desde dominios distintos
"Access-Control-Allow-Methods":"GET,POST,PUT,DELETE" //aquí especificas la lista de operacones que estás dispuesto a recibir cuando se trata de peticiones desde dominios distintos al dominio del servidor

EDIT

The way in which you define the headers in the HTTP responses of the server will vary depending on the language and / or framework that you are going to use, for example, in the framework ExpressJS for NodeJs would be as follows:

response.writeHead(200, {
    "Access-Control-Allow-Origin": "*", 
    "Access-Control-Allow-Headers":"Content-Type,Authorization", 
    "Access-Control-Allow-Methods":"GET,POST,PUT,DELETE"
});
response.end();     
    
answered by 02.11.2016 в 17:49