[英]How to pass object through NodeJS to FrontEnd
I did try other online solutions but I'm pretty bad and wanted a better understanding and also i couldn't make it work: 我曾尝试过其他在线解决方案,但我很糟糕,想要更好地理解,但我也无法使其工作:
Im setting up a web app and With NODe js for backend and when this someone makes a get request to "/" i want it to get all of the values from SQL like this: 我设置了一个Web应用程序,并使用NODe js作为后端,当有人向“ /”发出获取请求时,我希望它从SQL中获取所有值,如下所示:
con.query('SELECT * FROM customers', function(err, result) {
res.json(result);
}); }); Code When some one makes a get request to "/": 代码当有人向“ /”发出获取请求时:
//Home route
app.get('/', function(req, res){
(sql funciton here)
});
});
How do i pass the "result" variable to the front end.: 如何将“结果”变量传递给前端。:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
console.log(result);
</script>
All i want is it to print out the array but it says that its undefined. 我想要的只是将其打印出数组,但它表示未定义。
You have to make a request to server. 您必须向服务器发出请求。 For that you can use axios
or browsers fetch
api. 为此,您可以使用axios
或浏览器fetch
api。
axios.get("serverip/").then(res => {
console.log(res)
}
To fetch data from server, you need to make an API call. 要从服务器获取数据,您需要进行API调用。 XHR or XMLHttpRequest also allows to interact with servers. XHR或XMLHttpRequest也允许与服务器进行交互。
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("API response : ",xhttp.response);
};
var url = <API url>; /* http://localhost:3000 in your case */
xhttp.open("GET", url, true);
xhttp.send();
Please note that, if the API call is done from an html not rendered by the server handling the API (server running at localhost:3000 in your case), CORS(Cross Origin Resource Sharing) issue will arise and the browser will block the request. 请注意,如果API调用是通过处理API的服务器(在您的情况下,服务器在localhost:3000上运行)未呈现的html进行的,则会出现CORS(跨源资源共享)问题,浏览器将阻止该请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.