Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过post请求和fetch API传递json数据,并在express后端获取_Javascript_Json_Node.js_Ajax_Express - Fatal编程技术网

Javascript 通过post请求和fetch API传递json数据,并在express后端获取

Javascript 通过post请求和fetch API传递json数据,并在express后端获取,javascript,json,node.js,ajax,express,Javascript,Json,Node.js,Ajax,Express,我正在尝试学习express和FrontJavaScript。我正在尝试使用fetchapi通过post请求传递json数据,并希望使用express接收后端。 我的后端代码如下所示: const express = require('express'); const app = express(); const path = require('path'); app.get('/log', function(req, res){ console.log("Hi"); }); app

我正在尝试学习express和FrontJavaScript。我正在尝试使用fetchapi通过post请求传递json数据,并希望使用express接收后端。 我的后端代码如下所示:

const express = require('express');
const app = express();
const path = require('path');

app.get('/log', function(req, res){
    console.log("Hi");
});

app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'index.html')));
app.listen(3000, () => console.log('Example app listening on port 3000!'));
<!DOCTYPE html>
<html>
<head>
<title>Fetch And Express Test</title>
</head>
<body>

    <input id="a">
    <input id="b">
    <button> Click</button>
    <script>
        document.getElementsByTagName("button")[0].addEventListener("click",function(){
            console.log("Here");
            let aInput = document.getElementById("a").value;
            let bInput = document.getElementById("b").value;

            let json = {"a": aInput, "b": bInput};
            var data = new FormData();
            data.append( "json", JSON.stringify(json));

            fetch('http://localhost:3000/log', {
                method: "POST", // *GET, POST, PUT, DELETE, etc.
                mode: "cors", // no-cors, cors, *same-origin
                cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
                credentials: "same-origin", // include, same-origin, *omit
                headers: {
                    "Content-Type": "application/json; charset=utf-8",
                    // "Content-Type": "application/x-www-form-urlencoded",
                },
                redirect: "follow", // manual, *follow, error
                referrer: "no-referrer", // no-referrer, *client
                body: data, // body data type must match "Content-Type" header
            })
            .then(function(res){});
        });


    </script>
</body>
</html>
我的index.html文件如下所示:

const express = require('express');
const app = express();
const path = require('path');

app.get('/log', function(req, res){
    console.log("Hi");
});

app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'index.html')));
app.listen(3000, () => console.log('Example app listening on port 3000!'));
<!DOCTYPE html>
<html>
<head>
<title>Fetch And Express Test</title>
</head>
<body>

    <input id="a">
    <input id="b">
    <button> Click</button>
    <script>
        document.getElementsByTagName("button")[0].addEventListener("click",function(){
            console.log("Here");
            let aInput = document.getElementById("a").value;
            let bInput = document.getElementById("b").value;

            let json = {"a": aInput, "b": bInput};
            var data = new FormData();
            data.append( "json", JSON.stringify(json));

            fetch('http://localhost:3000/log', {
                method: "POST", // *GET, POST, PUT, DELETE, etc.
                mode: "cors", // no-cors, cors, *same-origin
                cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
                credentials: "same-origin", // include, same-origin, *omit
                headers: {
                    "Content-Type": "application/json; charset=utf-8",
                    // "Content-Type": "application/x-www-form-urlencoded",
                },
                redirect: "follow", // manual, *follow, error
                referrer: "no-referrer", // no-referrer, *client
                body: data, // body data type must match "Content-Type" header
            })
            .then(function(res){});
        });


    </script>
</body>
</html>

提取和表达测试
点击
document.getElementsByTagName(“按钮”)[0]。addEventListener(“单击”,函数(){
console.log(“此处”);
设aInput=document.getElementById(“a”).value;
让bInput=document.getElementById(“b”).value;
让json={“a”:aInput,“b”:bInput};
var data=new FormData();
data.append(“json”,json.stringify(json));
取('http://localhost:3000/log', {
方法:“发布”、//*获取、发布、放置、删除等。
模式:“cors”,//无cors,cors,*相同来源
缓存:“无缓存”,//*默认值,无缓存,重新加载,强制缓存,仅在缓存时
凭证:“同一来源”、//包括、同一来源、*省略
标题:{
“内容类型”:“应用程序/json;字符集=utf-8”,
//“内容类型”:“应用程序/x-www-form-urlencoded”,
},
重定向:“follow”、//手动、*follow、错误
推荐人:“无推荐人”,//无推荐人,*客户
body:data,//body数据类型必须与“Content type”头匹配
})
.然后(函数(res){});
});

这里的问题是,它不会记录“Hi”,而如果我删除fetch函数的第二个参数,只发送get请求,一切都会正常工作。有什么问题吗?

您的路由器只设置为登录
GET
请求,因此它不会登录
POST

app.get('/log',函数(req,res){
控制台日志(“Hi”);

});
您的路由器仅设置为登录
GET
请求,因此它不会登录
POST

app.get('/log',函数(req,res){
控制台日志(“Hi”);

});哦,我以为get只是一个函数名,现在它有意义了,非常感谢,8分钟后我就可以批准答案了。你能告诉我,我如何在app.post函数中检索post参数(json)吗?哦,我以为get只是一个函数名,现在它有意义了,非常感谢,8分钟后,我将能够批准答案。另外,您能否告诉我,如何在app.post函数中检索post参数(json)?