将node.js中的数据附加到现有html

时间:2016-12-10 21:28:56

标签: jquery node.js express cors

我在node.js中是个小说。可能是一个微不足道的问题。 我有server.js:

var express = require('express');
var cors = require('cors');
var app = express();
var path = require('path');
var request = require('request');
var cheerio = require("cheerio");

request({
  uri: "http://ptnpnh.ua",
}, function(error, response, body) {
  var $ = cheerio.load(body);

  $("[data-tab=toDay] .weatherNow .temp .temperature_value").each(function() {
    var link = $(this);
    var text = link.text();
    console.log(text);
  });
});

app.use(cors());

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
      res.sendFile(path.join(__dirname + '/index.html'));
    app.use(express.static('public'));
    app.use("/css", express.static(__dirname + '/css'));
    app.use("/color", express.static(__dirname + '/color'));
    app.use("/fontaw", express.static(__dirname + '/font-awesome'));
    app.use("/fonts", express.static(__dirname + '/fonts'));
    app.use("/img", express.static(__dirname + '/img'));
    app.use("/js", express.static(__dirname + '/js'));
    app.use("/node", express.static(__dirname + '/node_modules'));
});

app.post('/', function(req, res, next) {
});
app.listen(8080);

如何修改此代码,将“text”字符串放在现有“/index.html”的dom元素(例如id =“attachedText”)中?

2 个答案:

答案 0 :(得分:1)

你得到的几乎是正确的

var express = require('express');
var cors = require('cors');
var app = express();
var path = require('path');
var request = require('request');
var cheerio = require("cheerio");
var fs = require('fs') // notice this

request({
  uri: "http://ptnpnh.ua",
}, function(error, response, body) {
  var $ = cheerio.load(body);

  $("[data-tab=toDay] .weatherNow .temp .temperature_value").each(function() {
    var link = $(this);
    var text = link.text();
    console.log(text);
  });
});

app.use(cors()); // isnt this the same as below:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// you put it here, not assign it every request to /
app.use(express.static('public'));
app.use("/css", express.static(__dirname + '/css'));
app.use("/color", express.static(__dirname + '/color'));
app.use("/fontaw", express.static(__dirname + '/font-awesome'));
app.use("/fonts", express.static(__dirname + '/fonts'));
app.use("/img", express.static(__dirname + '/img'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/node", express.static(__dirname + '/node_modules'));


app.get('/', function(req, res, next) { 

    //res.sendFile(__dirname + '/index.html'); // just send file 

    fs.readFile(__dirname + '/index.html'), 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        //console.log(data);
        var $ = cheerio.load('<h2 class="title">Hello world</h2>')
        $('h2.title').text('Hello there!')
        $('h2').addClass('welcome')    

        res.set('Content-Type', 'text/html; charset=utf-8');
        res.send($.html());
    });
});

app.post('/', function(req, res, next) {

});
app.listen(8080);

答案 1 :(得分:0)

如果您不关心SEO(例如,在登录名后面等),而不必每次都在动态修改文件(例如,通过cheerio等)...

使用 JSONP

在您的index.html

<head>
    ...
  <script>function getServerData(data) { window.__SERVER_DATA__ = data; }</script>
  <script src="/api/server-data.json?callback=getServerData"></script>
</head>

在您的Node Express路由定义中

const app = express();

// ...

app.get('/api/server-data.json', (req, res) => {
  res.jsonp({
    foo: 'foo',
    bar: 'bar'
  });
});

然后只需从应用程序中的任何位置访问window.__SERVER_DATA__即可将其添加到DOM。