如何处理同构React + React路由器应用中的后置请求

时间:2015-06-26 17:44:17

标签: javascript reactjs react-router

我想构建同构react + react-router应用程序,经过几天的谷歌搜索,现在我可以实现只处理GET请求的同构应用程序。

这是我到目前为止所做的:

  1. 服务器使用react-router来处理所有请求
  2. react-router将调用驻留在与路径匹配的每个React视图中的fetchData个函数。
  3. 将之前获取的数据设置为React View的props并将其呈现为string
  4. 将之前作为全局变量string提取的window.__STATE__和数据注入HTML并将HTML传送到客户端
  5. 我们已成功从服务器呈现React App
  6. 当客户端完成加载我们的React App javascript后,它会尝试渲染。但是我们从window.__STATE__传递状态作为我们的React App的道具,而React将不会重新渲染,因为状态是相同的
  7. 问题是它不能用于POST / PUT / DELETE / WHATEVER请求。处理GET请求时,react-router包含有关paramsquery的信息。例如,如果我们有一条路线:/user/:uid并且客户请求此网址:/user/1?foo=bar,那么params将是:{uid: 1}query将是{{1} }}

    {foo: 'bar'}然后可以将其传递给react-router函数,以便知道获取fetchData为1的用户并对uid查询执行任何操作。

    在POST请求中,foo不知道POST参数。在服务器上,我们当然可以将POST参数传递给react-router函数,但客户端呢?它不知道POST参数是什么。

    有没有办法让服务器告诉客户有关POST参数的信息?以下是我的登录视图的示例。我希望当用户提交表单时,服务器会在出错时呈现错误消息,或者在成功时将其重定向到仪表板。

    fetchData.js

    fetchData

    server.js

    import whenKeys from 'when/keys';
    
    export default (authToken, routerState) => {
      var promises = routerState.routes.filter((match) => {
        return match.handler.fetchData;
      }).reduce((promises, match) => {
        promises[match.name] = match.handler.fetchData(authToken, routerState.params, routerState.query);
        return promises;
      }, {});
    
      return whenKeys.all(promises);
    }
    

    login.jsx

    ...
    app.use((req, res) => {
      const router = Router.create({
        routes,
        location: req.originalUrl,
        onError: next,
        onAbort: (abortReason) => {
          next(abortReason);
        }
      });
    
      router.run((Handler, state) => {
        fetchData(authToken, state).then((data) => {
          // render matched react View and generate the HTML
          // ...
        })
      });
    });
    ...
    

1 个答案:

答案 0 :(得分:22)

获得" POST"客户端上的数据

在客户端,您可以通过从表单输入中提取值来获取POST数据,其方式与您在正常提交表单时在服务器上收到的内容相对应。

使用POST数据

所以现在你有了POST数据,但是仍然存在无法将POST数据提供给React Router 0.13.x及更早版本的转换挂钩的问题。我创建了一个pull request for this feature,现在已经关闭,因为它是作为即将发布的v1.0版本重写的一部分而包含的。

它的要点是,位置现在有一个状态对象,用于搜集关于当前请求/转换所需的任何额外数据(这两个是偶然的):

  • 在服务器上,您一次只处理一个请求,因此您使用req.body
  • 中的数据创建静态位置
  • 在客户端上,您将状态对象(包含提取的表单数据)传递给transitionTo()

现在,您的转换挂钩能够在两个环境中接收相同的表单数据。如果事情进展顺利,太好了!如果事情进展顺利,您需要一种方法来传递错误并重新渲染表单。新州反对再次救援!使用transition.redirect()并传递输入数据和错误,您现在拥有了双方渲染所需的一切。

我现在没有详细介绍,因为v1.0仍处于测试阶段且v0.13.x无论如何都没有必要的API,但我有一个存储库,使用上面的pull请求来实现0.13.x的这个工作流程,您可以在此期间查看:

以下是该过程的一些粗略流程图:

包含错误并重新显示的服务器POST

Server flow diagram

客户端POST错误并重新显示

Client flow diagram

我还创建了一些与此场景相关的可重用模块:

  • get-form-data以表格的形式从表单的输入中获取数据。
  • react-auto-form提供了<AutoForm>,您可以使用<form>而不是onSubmit来接收表单输入中的所有数据作为其<form>处理程序的参数
  • react-router-form,即<Link> React路由器<a>action的内容 - 它处理触发到给定method的转换,传递body06-26 23:33:53.190: D/dalvikvm(1808): Not late-enabling CheckJNI (already on) 06-26 23:33:53.280: D/dalvikvm(1808): Trying to load lib /data/app- lib/com.levellabs.project.android-2/libgdx.so 0xb1fbed48 06-26 23:33:53.280: D/dalvikvm(1808): Added shared lib /data/app- lib/com.levellabs.project.android-2/libgdx.so 0xb1fbed48 06-26 23:33:53.280: D/dalvikvm(1808): No JNI_OnLoad found in /data/app- lib/com.levellabs.project.android-2/libgdx.so 0xb1fbed48, skipping init 06-26 23:33:53.280: D/(1808): HostConnection::get() New Host Connection established 0xb90f3dc0, tid 1808 06-26 23:33:53.460: I/AndroidInput(1808): sensor listener setup 06-26 23:33:53.550: W/EGL_emulation(1808): eglSurfaceAttrib not implemented 06-26 23:33:53.550: D/OpenGLRenderer(1808): Enabling debug mode 0 06-26 23:33:53.560: D/(1808): HostConnection::get() New Host Connection established 0xb910b590, tid 1823 06-26 23:33:53.600: W/GL2JNIView(1808): creating OpenGL ES 2.0 context 06-26 23:33:53.800: D/dalvikvm(1808): Trying to load lib /data/app- lib/com.levellabs.project.android-2/libgdx.so 0xb1fbed48 06-26 23:33:53.800: D/dalvikvm(1808): Shared lib '/data/app- lib/com.levellabs.project.android-2/libgdx.so' already loaded in same CL 0xb1fbed48 06-26 23:33:53.800: I/GL2(1808): all initialized 2 06-26 23:33:53.800: I/AndroidGraphics(1808): OGL renderer: Android Emulator OpenGL ES Translator (GeForce GTX 770/PCIe/SSE2) 06-26 23:33:53.800: I/AndroidGraphics(1808): OGL vendor: Google (NVIDIA Corporation) 06-26 23:33:53.800: I/AndroidGraphics(1808): OGL version: OpenGL ES 2.0 (4.5.0 NVIDIA 350.12) 06-26 23:33:53.800: I/AndroidGraphics(1808): OGL extensions: GL_EXT_debug_marker GL_OES_EGL_image GL_OES_EGL_image_external GL_OES_depth24 GL_OES_depth32 GL_OES_element_index_uint GL_OES_texture_float GL_OES_texture_float_linear GL_OES_compressed_paletted_texture GL_OES_compressed_ETC1_RGB8_texture GL_OES_depth_texture GL_OES_texture_half_float GL_OES_texture_half_float_linear GL_OES_packed_depth_stencil GL_OES_vertex_half_float GL_OES_texture_npot GL_OES_rgb8_rgba8 06-26 23:33:53.800: E/EGL_emulation(1808): [getAttribValue] Bad attribute idx 06-26 23:33:53.800: E/EGL_emulation(1808): tid 1823: eglGetConfigAttrib(605): error 0x3004 (EGL_BAD_ATTRIBUTE) 06-26 23:33:53.800: E/EGL_emulation(1808): [getAttribValue] Bad attribute idx 06-26 23:33:53.800: E/EGL_emulation(1808): tid 1823: eglGetConfigAttrib(605): error 0x3004 (EGL_BAD_ATTRIBUTE) 06-26 23:33:53.800: I/AndroidGraphics(1808): framebuffer: (5, 6, 5, 0) 06-26 23:33:53.800: I/AndroidGraphics(1808): depthbuffer: (24) 06-26 23:33:53.800: I/AndroidGraphics(1808): stencilbuffer: (0) 06-26 23:33:53.800: I/AndroidGraphics(1808): samples: (0) 06-26 23:33:53.800: I/AndroidGraphics(1808): coverage sampling: (false) 06-26 23:33:53.810: I/AndroidGraphics(1808): Managed meshes/app: { } 06-26 23:33:53.810: I/AndroidGraphics(1808): Managed textures/app: { } 06-26 23:33:53.810: I/AndroidGraphics(1808): Managed cubemap/app: { } 06-26 23:33:53.810: I/AndroidGraphics(1808): Managed shaders/app: { } 06-26 23:33:53.810: I/AndroidGraphics(1808): Managed buffers/app: { } 06-26 23:33:55.540: I/dalvikvm(1808): Could not find method aurelienribon.tweenengine.TweenManager.update, referenced from method com.levellabs.project.GameScreen.render 06-26 23:33:55.540: W/dalvikvm(1808): VFY: unable to resolve virtual method 369: Laurelienribon/tweenengine/TweenManager;.update (F)V 06-26 23:33:55.540: D/dalvikvm(1808): VFY: replacing opcode 0x6e at 0x0008 06-26 23:33:55.540: D/dalvikvm(1808): GC_FOR_ALLOC freed 407K, 14% free 2931K/3392K, paused 2ms, total 2ms 06-26 23:33:55.540: E/dalvikvm(1808): Could not find class 'aurelienribon.tweenengine.TweenManager', referenced from method com.levellabs.project.GameScreen.show 06-26 23:33:55.540: W/dalvikvm(1808): VFY: unable to resolve new-instance 100 (Laurelienribon/tweenengine/TweenManager;) in Lcom/levellabs/project/GameScreen; 06-26 23:33:55.540: D/dalvikvm(1808): VFY: replacing opcode 0x22 at 0x001e 06-26 23:33:55.540: D/dalvikvm(1808): DexOpt: unable to opt direct call 0x0170 at 0x20 in Lcom/levellabs/project/GameScreen;.show 06-26 23:33:55.540: I/dalvikvm(1808): Failed resolving Lcom/levellabs/project/tween/SpriteAccessor; interface 98 'Laurelienribon/tweenengine/TweenAccessor;' 06-26 23:33:55.540: W/dalvikvm(1808): Link of class 'Lcom/levellabs/project/tween/SpriteAccessor;' failed 06-26 23:33:55.540: D/dalvikvm(1808): DexOpt: unable to opt direct call 0x345e at 0x29 in Lcom/levellabs/project/GameScreen;.show 06-26 23:33:55.540: I/dalvikvm(1808): Failed resolving Lcom/levellabs/project/GameScreen$1; interface 99 'Laurelienribon/tweenengine/TweenCallback;' 06-26 23:33:55.540: W/dalvikvm(1808): Link of class 'Lcom/levellabs/project/GameScreen$1;' failed 06-26 23:33:55.540: D/dalvikvm(1808): DexOpt: unable to opt direct call 0x3434 at 0x54 in Lcom/levellabs/project/GameScreen;.show 06-26 23:33:55.660: D/dalvikvm(1808): GC_FOR_ALLOC freed 71K, 9% free 3192K/3472K, paused 2ms, total 2ms 06-26 23:33:56.120: W/dalvikvm(1808): threadid=11: thread exiting with uncaught exception (group=0xb1cecb20) 06-26 23:33:56.120: E/AndroidRuntime(1808): FATAL EXCEPTION: GLThread 75 06-26 23:33:56.120: E/AndroidRuntime(1808): Process: com.levellabs.project.android, PID: 1808 06-26 23:33:56.120: E/AndroidRuntime(1808): java.lang.NoClassDefFoundError: aurelienribon.tweenengine.TweenManager 06-26 23:33:56.120: E/AndroidRuntime(1808): at com.levellabs.project.GameScreen.show(GameScreen.java:68) 06-26 23:33:56.120: E/AndroidRuntime(1808): at com.badlogic.gdx.Game.setScreen(Game.java:61) 06-26 23:33:56.120: E/AndroidRuntime(1808): at com.levellabs.project.Project.create(Project.java:24) 06-26 23:33:56.120: E/AndroidRuntime(1808): at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphi cs.java:241) 06-26 23:33:56.120: E/AndroidRuntime(1808): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1512) 06-26 23:33:56.120: E/AndroidRuntime(1808): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240) 06-26 23:33:56.130: I/AndroidInput(1808): sensor listener tear down 06-26 23:33:56.130: I/AndroidGraphics(1808): Managed meshes/app: { } 06-26 23:33:56.130: I/AndroidGraphics(1808): Managed textures/app: { } 06-26 23:33:56.130: I/AndroidGraphics(1808): Managed cubemap/app: { } 06-26 23:33:56.130: I/AndroidGraphics(1808): Managed shaders/app: { } 06-26 23:33:56.130: I/AndroidGraphics(1808): Managed buffers/app: { } (表单数据)状态 - 这将很快更新为v1.0。