How to make 'Post' request to local server?

Viewed 4011

I have project bundled on Webpack4, I need to take some info in form inputs from and write it to txt file. I'm new in developing, so sorry if question is stupid

So I created node.js server, on which i need to post this data and then write to txt file. When i trying to make 'Post' request to my localhost, it gives error 'Access to XMLHttpRequest at 'file:///E:/server/localhost:3000' from origin 'http://localhost:9000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.'. How to fix this problem.


    const http = require('http');
    const fs = require('fs');
    const path = require('path');

    const server = http.createServer((req, res) => 
        {res.writeHead(200, {
            'Content-Type':'text/html'
        })
        res.end('ggwp')}
        )
    server.listen(3000, () =>{
        console.log('ok')
    })    

```here's my server

    const bookForm = document.querySelector(".book-form");
    const select = document.querySelector(".select");
    const name = document.getElementsByName('name');
    const number = document.getElementsByName('phone_number');
    const xhr = new XMLHttpRequest();

    export let fragment = '';

    export function abc() {
      bookForm.addEventListener("submit", e => {
        e.preventDefault();
        console.log(fs);
        fragment += name[0].value + ' ' +number[0].value + ' ' + select.options[select.selectedIndex].text;
        xhr.open('POST', 'file:///E:/server/localhost:3000', true)
        xhr.send(fragment)

    xhr.onreadystatechange = function() { // (3)
      if (xhr.readyState != 4) return;

      if (xhr.status != 200) {
        console.log(xhr.status, xhr.statusText)
        alert(xhr.status + ': ' + xhr.statusText);
      } else {
        alert(xhr.responseText);
      }

    }
      });
2 Answers

You will need to add CORS library to your project CORS library usage

Add below code where you include the CORS library app.use(cors({ allowedOrigins: [ 'http://localhost:9000' ] }));

Try to change your code to xhr.open('POST', 'localhost:3000', true)

Related