Is there a way to send data from client to server in angular universal?

余生颓废 提交于 2019-12-11 05:28:44

问题


We are using angular 5.2.8 with nguniversal/express-engine 5.0.0-beta.6 and we are using external payment services. The payment system requires a form to be posted to their URL and has an input for callbackURL.

The callback from that request sends us back a POST request with data. We need to post that data to our backend with user credentials. In angular we can't receive post requests.

I have tried some options for the solution but none of them worked so far:

  • Listening for posts in express and then transfer data to angular
  • Trying to send cookies or user information to server for making a server to server request to our backend.

I need to either send the contents of the callback post to client side, or pass user credentials to server side.


回答1:


In an Angular Universal project, in the server.ts file, we write the following kind of code.

So, basically, we are redirecting the browser to the index.html for all the Angular routes. However, the URLs starting with /api/* are excluded as they below to the APIs. It seems you need to have the callback URL starting with /api/* and that's where you need to have an HTTP POST API to handle the call.

app.get('/api/*', (req, res) => {

});

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});



回答2:


Your first approach should work. To be really generic, you could provide the express request toyour angular universal app, so that components/services needed the request's values can access it

server.ts

app.engine('html', (_, options, callback) => {


  renderModuleFactory(AppServerModuleNgFactory, {
    // Our index.html
    document: template,
    url: options.req.path,
    extraProviders: [
      {
        provide: 'httpRequest',
        useValue: options.req,

      }
    ]
  }).then(html => {

    callback(null, html);
  });
});

//Handle your post
app.post('/yourpostUrl', (req, res) => {

  res.render(join(DIST_FOLDER, 'browser', 'index.html'), {req});
});

Then provide the request angular side. Don't forget to make it as Optional so that it does not thrown an error client side

component.ts

 constructor(@Optional() @Inject('httpRequest') private httpRequest: any)
  {
      //here you can use httpRequest's valuesy
  }


来源:https://stackoverflow.com/questions/49572873/is-there-a-way-to-send-data-from-client-to-server-in-angular-universal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!