Can Bakış
Can Bakış

Reputation: 11

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

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:

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

Upvotes: 1

Views: 2008

Answers (2)

David
David

Reputation: 34445

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
  }

Upvotes: 1

Saptarshi Basu
Saptarshi Basu

Reputation: 9283

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 });
});

Upvotes: 0

Related Questions