最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何使用Express设置我的sitemap.xml的'X

IT培训 admin 8浏览 0评论

如何使用Express设置我的sitemap.xml的'X

如何将我的sitemap.xml(以及此文件)的HTTP标头“X-Robots-Tag”设置为“noindex,follow”with express?

sitemap.xml位于我的应用程序的根目录。

这是我的快速配置的片段:

快递/ development.js

const express = require('express')
const webpack = require('webpack')
const cors = require('cors')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const webpackHotServerMiddleware = require('webpack-hot-server-middleware')
const config = require('./../webpack/webpack.development.config.js')

const app = express()
const compiler = webpack(config)
const PORT = process.env.PORT || 3000

app.use(cors())
app.use(express.static('build'))
app.use(express.static('public'))

...

我试过这个:

... 

app.get('/sitemap.xml', res => {
  res.setHeader('X-Robots-Tag', 'noindex, follow')
})

和这个:

app.get('/sitemap.xml', res => {
  res.set('X-Robots-Tag', 'noindex, follow')
})

另外,如何查看标题是否已更新。

我试过了:$curl -v localhost:3000/sitemap.xml

但是标题中没有“X-Robots-Tag”,所以我认为它不起作用。

回答如下:

如docs中所述,静态中间件接受一个options参数,您可以在其中设置setHeaders函数以根据路径修改响应头:

const fs = require('fs');
const path = require('path');
const http = require('http');

const express = require('express');

const publicDirectoryPath = path.join(__dirname, './public');

// the following creates and a public directory in the script directory and populates it with some files (for the sake of this demo).

// create the public directory if it doesn't exist
if (!fs.existsSync(publicDirectoryPath)) {
  fs.mkdirSync(publicDirectoryPath);
}

// create a sample sitemap.xml (for the sake of this demo)
const siteMapXml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps/schemas/sitemap/0.9">
   <url>
      <loc>http://www.example/</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
</urlset>`;
fs.writeFileSync(path.join(publicDirectoryPath, './sitemap.xml'), siteMapXml);

// create a sample index.html
const indexHtml = `<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8">
  <title>Demo</title>

  <p>It works!</p>
</html>`;
fs.writeFileSync(path.join(publicDirectoryPath, './index.html'), indexHtml);

// setup and start the express server

const app = express();
const PORT = process.env.PORT || 3000;

app.use(
  express.static(path.join(__dirname, "public"), {
    setHeaders: (res, path) => {
      if (path.endsWith("sitemap.xml")) {
        res.setHeader("X-Robots-Tag", "noindex, follow");
      }
    }
  })
);

app.listen(PORT);

// check response headers

const makeGetRequestAndPrintHeaders = (path) => {
  const options = {
    hostname: 'localhost',
    port: PORT,
    path,
    method: 'GET'
  };

  const req = http.request(options, (res) => {
    console.log(`GET ${path}`);
    console.log(JSON.stringify(res.headers, null, 2));
  });

  req.end();
}

makeGetRequestAndPrintHeaders('/index.html');
makeGetRequestAndPrintHeaders('/sitemap.xml');

// example output
/*
GET /index.html                                     
{                                                   
  "x-powered-by": "Express",                        
  "accept-ranges": "bytes",                         
  "cache-control": "public, max-age=0",             
  "last-modified": "Wed, 13 Feb 2019 14:28:26 GMT", 
  "etag": "W/\"6b-168e74243aa\"",                   
  "content-type": "text/html; charset=UTF-8",       
  "content-length": "107",                          
  "date": "Wed, 13 Feb 2019 14:28:26 GMT",          
  "connection": "close"                             
}                                                   
GET /sitemap.xml                                    
{                                                   
  "x-powered-by": "Express",                        
  "x-robots-tag": "noindex, follow",                
  "accept-ranges": "bytes",                         
  "cache-control": "public, max-age=0",             
  "last-modified": "Wed, 13 Feb 2019 14:28:26 GMT", 
  "etag": "W/\"113-168e74243a9\"",                  
  "content-type": "text/xml; charset=UTF-8",        
  "content-length": "275",                          
  "date": "Wed, 13 Feb 2019 14:28:26 GMT",          
  "connection": "close"                             
}
*/

如何使用Express设置我的sitemap.xml的'X

如何将我的sitemap.xml(以及此文件)的HTTP标头“X-Robots-Tag”设置为“noindex,follow”with express?

sitemap.xml位于我的应用程序的根目录。

这是我的快速配置的片段:

快递/ development.js

const express = require('express')
const webpack = require('webpack')
const cors = require('cors')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const webpackHotServerMiddleware = require('webpack-hot-server-middleware')
const config = require('./../webpack/webpack.development.config.js')

const app = express()
const compiler = webpack(config)
const PORT = process.env.PORT || 3000

app.use(cors())
app.use(express.static('build'))
app.use(express.static('public'))

...

我试过这个:

... 

app.get('/sitemap.xml', res => {
  res.setHeader('X-Robots-Tag', 'noindex, follow')
})

和这个:

app.get('/sitemap.xml', res => {
  res.set('X-Robots-Tag', 'noindex, follow')
})

另外,如何查看标题是否已更新。

我试过了:$curl -v localhost:3000/sitemap.xml

但是标题中没有“X-Robots-Tag”,所以我认为它不起作用。

回答如下:

如docs中所述,静态中间件接受一个options参数,您可以在其中设置setHeaders函数以根据路径修改响应头:

const fs = require('fs');
const path = require('path');
const http = require('http');

const express = require('express');

const publicDirectoryPath = path.join(__dirname, './public');

// the following creates and a public directory in the script directory and populates it with some files (for the sake of this demo).

// create the public directory if it doesn't exist
if (!fs.existsSync(publicDirectoryPath)) {
  fs.mkdirSync(publicDirectoryPath);
}

// create a sample sitemap.xml (for the sake of this demo)
const siteMapXml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps/schemas/sitemap/0.9">
   <url>
      <loc>http://www.example/</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
</urlset>`;
fs.writeFileSync(path.join(publicDirectoryPath, './sitemap.xml'), siteMapXml);

// create a sample index.html
const indexHtml = `<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8">
  <title>Demo</title>

  <p>It works!</p>
</html>`;
fs.writeFileSync(path.join(publicDirectoryPath, './index.html'), indexHtml);

// setup and start the express server

const app = express();
const PORT = process.env.PORT || 3000;

app.use(
  express.static(path.join(__dirname, "public"), {
    setHeaders: (res, path) => {
      if (path.endsWith("sitemap.xml")) {
        res.setHeader("X-Robots-Tag", "noindex, follow");
      }
    }
  })
);

app.listen(PORT);

// check response headers

const makeGetRequestAndPrintHeaders = (path) => {
  const options = {
    hostname: 'localhost',
    port: PORT,
    path,
    method: 'GET'
  };

  const req = http.request(options, (res) => {
    console.log(`GET ${path}`);
    console.log(JSON.stringify(res.headers, null, 2));
  });

  req.end();
}

makeGetRequestAndPrintHeaders('/index.html');
makeGetRequestAndPrintHeaders('/sitemap.xml');

// example output
/*
GET /index.html                                     
{                                                   
  "x-powered-by": "Express",                        
  "accept-ranges": "bytes",                         
  "cache-control": "public, max-age=0",             
  "last-modified": "Wed, 13 Feb 2019 14:28:26 GMT", 
  "etag": "W/\"6b-168e74243aa\"",                   
  "content-type": "text/html; charset=UTF-8",       
  "content-length": "107",                          
  "date": "Wed, 13 Feb 2019 14:28:26 GMT",          
  "connection": "close"                             
}                                                   
GET /sitemap.xml                                    
{                                                   
  "x-powered-by": "Express",                        
  "x-robots-tag": "noindex, follow",                
  "accept-ranges": "bytes",                         
  "cache-control": "public, max-age=0",             
  "last-modified": "Wed, 13 Feb 2019 14:28:26 GMT", 
  "etag": "W/\"113-168e74243a9\"",                  
  "content-type": "text/xml; charset=UTF-8",        
  "content-length": "275",                          
  "date": "Wed, 13 Feb 2019 14:28:26 GMT",          
  "connection": "close"                             
}
*/
发布评论

评论列表 (0)

  1. 暂无评论