wuno
wuno

Reputation: 9875

Nuxt application using Express won't allow POST routes to be hit externally of application

Background

I have a NUXT application that renders vue templates as you would expect. I have a need to hit some Express routes in the application from external applications client side.

I can hit GET routes from external applications but POST requests fail with a error 404.

Example

Express

This works

router.get('/test/get', (req, res, next) => {
  res.json({ message: "Global PDF Generator is configured correctly", status: "operational" })
});

This fails with 404

router.post('/test/post', (req, res, next) => {
  res.json({ message: "Global PDF Generator is configured correctly", status: "operational" })
});

Inside of the Nuxt application and within any of the vue components I can hit the POST routes like this,

fetch('api/v1/pdf', { method: 'POST' }

But if we try to do something like this it fails,

fetch('localhost:3000/api/v1/pdf', { method: 'POST' }

The second example is important because obvioulsy that is how I would have to hit an end point in this application from an outside application.

What I can not figure out is why the GET requests work and do not get a 404 while the POST requests continue to get a 404 from external applications.

Question

How can I create an externally accessible Express POST end point in my NUXT application so that it will be directly accessible from an external source?

Upvotes: 1

Views: 1394

Answers (2)

G'ofur N
G'ofur N

Reputation: 2652

This is because when the NuxtJs app on production it sees only page routes not server route. You should use NuxtJs serverMiddleware. You can find it here from NuxtJs API

Upvotes: 0

clockwatcher
clockwatcher

Reputation: 3363

Not as an answer but just so I can format things and demonstrate that something else must be going on. This minimal example works fine for me.

vue init nuxt-community/express-template sample_post
cd sample_post
npm install

Modify api/routes/users.js adding a post route:

router.post('/test', function(req, res, next) {
   res.json(message: 'hello');
});

Start up the service:

npm run dev

Verify it returns a post from an external request successfully:

curl -X POST http://localhost:3000/api/test
{"message":"hello"}

So something else must be going on somewhere.

Upvotes: 1

Related Questions