【问题标题】:How to make 'Post' request to local server?如何向本地服务器发出“发布”请求?
【发布时间】:2019-10-27 21:48:04
【问题描述】:

我在 Webpack4 上捆绑了项目,我需要从表单输入中获取一些信息并将其写入 txt 文件。 我是开发新手,如果问题很愚蠢,请见谅

所以我创建了 node.js 服务器,我需要在该服务器上发布这些数据,然后写入 txt 文件。当我尝试向我的本地主机发出“发布”请求时,它会给出错误“访问 XMLHttpRequest at 'file:///E:/​​server/localhost:3000' from origin 'http://localhost:9000'已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https.'。如何解决这个问题。


    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);
      }

    }
      });

【问题讨论】:

  • 使用 expressjs 的生成器可以帮助您设置一种简单的方式来接受请求。
  • 您不能发布到file:// url,实际上您不能向任何file:// url 发出请求(获取、发布等),出于安全原因,浏览器不允许这样做。您是指指向同一个本地主机,例如http://localhost:9000,还是指向在端口3000 上运行的不同服务器,例如http://localhost:3000

标签: javascript node.js webpack


【解决方案1】:

您需要将 CORS 库添加到您的项目中 CORS library usage

在您包含 CORS 库的地方添加以下代码 app.use(cors({ allowedOrigins: [ 'http://localhost:9000' ] }));

【讨论】:

    【解决方案2】:

    尝试将您的代码更改为xhr.open('POST', 'localhost:3000', true)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2016-08-01
      • 2016-02-27
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多