简体   繁体   English

发布请求-以json格式发送数据

[英]Post request - sent data in json format

I have a study project. 我有一个学习项目。 Have a simple form with input and button. 使用带有输入和按钮的简单表单。 Need to save an input value into JSON file. 需要将输入值保存到JSON文件中。 HTML HTML

<form action="/" method="post" id="emailForm">
    <input type="email" id="email" name="email" placeholder="Enter email for newsletter">
    <button type="submit" id="subscribe" value=""><i class="fas fa-chevron-right"></i></button>
</form>

JS to convert data into JSON format JS将数据转换为JSON格式

$('#subscribe').on('click', function (event) {
        // prevent from reloading the page
        event.preventDefault();
        // checking validity of input
        if (ValidateEmail()) {
            var formData = $("#emailForm").serializeArray();
            $.each(formData, function () {
                if (jsonData[this.name]) {
                    if (!jsonData[this.name].push) {
                        jsonData[this.name] = [jsonData[this.name]];
                    }
                    jsonData[this.name].push(this.value || '');
                } else {
                    jsonData[this.name] = this.value || '';
                }

                jsonData = JSON.stringify(jsonData);

            });

            console.log(jsonData);


            $.ajax({
                url: "app.js",
                type: "POST",
                dataType: 'json',
                data: jsonData

            }); 
            alert('Email saved!');
            return jsonData;

        } else {
            console.log('email not saved');
        }
    });

app.js app.js

const fs = require('fs');

fs.readFile('email.json', (err, data) => {  
    if (err) throw err;
    let email = JSON.parse(data);
    console.log('original' + email);
});
fs.writeFileSync('email.json', jsonData);  
console.log('done');

the problem is with accessing file app.js - first, it's blocked by chrome 问题出在访问文件app.js-首先,它被chrome阻止了

Access to XMLHttpRequest at 'file:///D:/HTML/Try%20it/acad/master/app.js' from origin 'null' has been blocked by CORS policy: Cross-origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https CORS策略已阻止从源“ null”访问“ file:/// D:/HTML/Try%20it/acad/master/app.js”处的XMLHttpRequest:协议方案仅支持跨域请求: HTTP,数据,chrome,chrome扩展名,https

Tried to run a local server with node.js and received Error 405 (Method Not Allowed). 尝试使用node.js运行本地服务器,并收到错误405(不允许使用方法)。

Your app.js is just a script, that start to read a file, write one by blocking the thread, print 'done' and shutdown. 您的app.js只是一个脚本,它开始读取文件,通过阻塞线程来写入文件,打印“完成”并关闭。 No HTTP server, no request handling... 没有HTTP服务器,没有请求处理...

What you need first is to set up a HTTP server, this can be done with the native http node.js module, or with other modules (like express ), so that you listen for events, and trigger code when a the server is called. 您首先需要设置一个HTTP服务器,这可以通过本机http node.js模块或其他模块(例如express )完成,以便侦听事件并在调用服务器时触发代码。

Also, the http-server is made to quickly render some files, trying to POST to a text file obviously do nothing, and if you were to GET it, you would simply get you text file, which do you no good. 此外, http-server是由快速呈现一些文件,试图POST到一个文本文件明明什么都不做,如果你要GET它,你只会让你的文本文件,这对你没有好处。

So depending on what are your homework constraint, you need to either check http , or express documentation, set up a valid HTTP server, and on that call, correctly write to your file. 因此,根据您的家庭作业约束,您需要检查httpexpress文档,设置有效的HTTP服务器,然后在该调用中正确写入文件。

(Tips: Do not use ...Sync function in node.js, unless you really do know what you are doing, and check what "asynchronous" functions are, you will need it) (提示:请勿在node.js中使用...Sync函数,除非您真的知道自己在做什么,并检查什么是“异步”函数,否则将需要它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM