![](/img/trans.png)
[英]How to send and get JSON data from Node.js into HTML using Node.js
[英]how to send data from html to node js?
下面是我的html
代码,我从这里通过 JQuery 发送数据
<script type="text/javascript">
$(document).ready(function(){
sndt();
function sndt(nid){
$.ajax({
url:"localhost:3000/client",
method:"POST",
data:{nid,test:"dooo"},
success:function(data){
$("#video").html(data);
},
error:function(data){
console.log("ZUBAIR");
}
})
}
})
</script>
现在我想在我的节点 js 控制台中显示这个测试数据这是我在节点 js 中的代码
require("dotenv").config();
const express = require("express");
const path = require("path");
var cons = require('consolidate');
var bodyParser = require('body-parser');
const app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.urlencoded({extended:false}));
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'www'));
app.set('view engine', 'html');
var PORT = process.env.PORT || 3000; // signalingServerPort
var localHost = "http://localhost:" + PORT; // http
app.use(express.static(path.join(__dirname, "www")));
// Remove trailing slashes in url
app.use(function (req, res, next) {
if (req.path.substr(-1) === "/" && req.path.length > 1) {
let query = req.url.slice(req.path.length);
res.redirect(301, req.path.slice(0, -1) + query);
} else {
next();
}
});
// no room name specified to join
app.get("/join/", function (req, res) {
res.redirect("/");
});
// join to room
app.post("/join/*", function (req, res) {
var t = (req.body.test);
console.log("ttttt"+ t);
if (Object.keys(req.query).length > 0) {
console.log("redirect:" + req.url + " to " + url.parse(req.url).pathname);
res.redirect(url.parse(req.url).pathname);
} else {
var t = (req.body.test);
console.log("ttttt"+ t);
res.sendFile(path.join(__dirname, "www/client.html"));
}
});
这些是我面临的错误
Access to XMLHttpRequest at 'localhost:3000/client' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
和
jquery-2.2.4.js:9175 POST localhost:3000/client net::ERR_FAILED
这是我的节点 js 代码,我哪里出错了??谢谢?
当您从前端调用到后端时,这是一个 cors 问题,您必须在后端代码中启用 cors
所以你需要先安装 cors 通过运行以下命令
npm install cors
安装后,在节点 js 代码中输入 go 并导入 cors 并使用 cors ,因为我使用了以下代码
var cors = require('cors')
var app = express()
app.use(cors())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.