基于URL参数显示动态网页内容(Parse Cloud, Express, ejs)



我是新的编程和这个项目,我正在构建一个web应用程序使用Parse.com云代码和快递。结构如下:

  • app.js (Express相关代码)
  • 视图/你好。ejs(模板)
  • main.js(云函数)

我也有一个iOS应用程序,可以在Facebook上发布链接,看起来像这样:myapp.parseapp.com/hello?objectid。当Facebook用户点击该链接并被重定向到web应用程序时,web应用程序将自动根据提供的objectid对模板进行res.render。然后使用objectid从使用Parse的Parse类获取一些数据,这些数据将显示在页面上。查询,但我的障碍不是Parse.Query.

为了检查objectid是否被服务器成功捕获,我尝试了以下代码来呈现模板并将objectid插入text变量的占位符中,但是put objectid here在加载页面时没有更改为提供的objectid。谁能告诉我哪里出了问题,或者我是否应该用另一种方法来做这件事?

hello.ejs (template):

<!DOCTYPE html>
<html>
  <head>
    <title>My Web App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
        $.post('/hello', {oid: window.location.toString().split("?")[1]});
    </script>
  </head>
  <body>
    <p><%= text %></p>
  </body>
</html>

app.js (express):

// Initialize Express in Cloud Code.
var express = require('express');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(express.bodyParser());    // Middleware for reading request body
// Render view
app.get('/hello', function(req, res) {
    res.render('hello', { text: 'put objectid here' });
});
app.post('/hello', function(req, res) {
    res.render('hello', { text: req.body.oid });
});
app.listen();

经过更多的研究,我看到了这篇文章:如何在express node js中获得url参数。决定试一试,果然成功了!这就是解决方案。

URL改为:myapp.parseapp.com/hello?id=objectid

不再需要<head>中的<script>。最终代码如下所示:

hello.ejs (template):

<!DOCTYPE html>
<html>
  <head>
    <title>My Web App</title>
  </head>
  <body>
    <p><%= text %></p>
  </body>
</html>

app.js (express):

// Initialize Express in Cloud Code.
var express = require('express');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(express.bodyParser());    // Middleware for reading request body
// Render view
app.get("/hello", function(req, res) {
  res.render('hello', { text: req.param("id") });
});
app.listen();

干杯!

最新更新