在server.js(Express / NextJS)中获取301重定向数据

时间:2018-09-28 15:39:45

标签: reactjs express fetch next.js

我正在使用express和next js进行项目开发,并且我找到了一个很好的示例,说明如何在server.js文件中为重定向设置数据数组。但是,如果可能的话,我想在WordPress中构建一个插件,该插件将允许用户提交重定向数据,以便由不具备技术知识的人员进行管理。我的问题是,在此示例中是否可以在server.js文件中获取数据以替换数据?

const express = require('express')
const next = require('next')
const { join } = require('path')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

//This is the data I want to fetch through the WP Rest API
const redirects = [
  { from: '/old-link-1', to: '/new-link-1' },
  { from: '/old-link-2', to: 'https://externalsite.com/new-link-2' },
]

app.prepare().then(() => {
  const server = express()

  redirects.forEach(({ from, to, type = 301, method = 'get' }) => {
    server[method](from, (req, res) => {
      res.redirect(type, to)
    })
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

2 个答案:

答案 0 :(得分:1)

是的,我相信有可能做类似的事情。

该库将允许您在Express https://github.com/request/request

中发出API请求

执行如下:

 var request = require('request');
 request('http://www.google.com', function (error, response, body) {
   if (!error && response.statusCode == 200) {
     console.log(body) // Print the google web page.
   }
 })

下一步是使用您要创建的所有301在wordpress中创建一个端点:

function my_custom_endpoint(){
  return 'Hey look, its some data';
}

// Register the rest route here.
add_action( 'rest_api_init', function () {
register_rest_route( 'yournamespace/v1', 'my_custom_endpoint',array(
    'methods'  => 'GET',
    'callback' => 'my_custom_endpoint'
  ));
});

祝你好运,编码愉快!

答案 1 :(得分:0)

因此,以防万一其他人偶然发现以编程方式添加源自WordPress安装的重定向的问题,这是可以做到的。我的技术堆栈是React,Next.js,它带有Express服务器,该服务器从WordPress安装中提取数据,而WordPress安装位于网络的其他位置。

WordPress:

1)创建一个空白的WordPress插件(Google是您的朋友)

2)在您的插件中创建一个激活钩,以创建一个数据库(同样,对于每个条目,Google均带有“ to_url”和“ from_url”。

3)在插件中注册一条“休息路线”(类似于上述Tanner的答案)

  • 此Rest Route应该从数据库中提取您的信息,并以以下格式将其作为数组返回:

    [   {'from':'/ about','to':'/ about-us'},   {'from':'/ test3','to':'/ banks / testing-page'}, ]

4)创建一个插件管理页面,该页面的格式允许用户向该数据库添加条目。随着数据库的增长,来自其余api的响应也将增长,并且重定向将无缝地包含在项目中。

5)在您的React server.js中,您将需要以下设置

const request = require("request");
let redirects;
request('https://yourwebsite.com/wp-json/YOUR-ROUTE/v2/redirects', function (error, response, body) {
   if (!error && response.statusCode == 200) {
      redirects = JSON.parse(body);
   }
 })
redirects.forEach(({ from, to, type = 301, method = 'get' }) => {
          server[method](from, (req, res) => {
            res.redirect(type, to)
          })
        });

注意事项:请确保在使用php中的表单处理数据时,正在采取适当的预防措施来清理并转义所有内容。