gpt4 book ai didi

javascript - 如何向本地服务器发出 'Post' 请求?

转载 作者:行者123 更新时间:2023-11-30 06:50:02 27 4
gpt4 key购买 nike

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

所以我创建了 node.js 服务器,我需要在其上发布此数据,然后写入 txt 文件。当我尝试向我的本地主机发出“发布”请求时,它会给出错误“从来源'http://localhost:9000访问'file:///E:/​​server/localhost:3000'处的 XMLHttpRequest” '已被 CORS 策略阻止:跨源请求仅支持协议(protocol)方案:http、数据、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);
}

}
});

最佳答案

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

在包含 CORS 库的位置添加以下代码
app.use(cors({
允许来源:[
'http://localhost:9000'
]
}));

关于javascript - 如何向本地服务器发出 'Post' 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58583647/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com