Reputation: 28
I want to use Axios to make client AJAX calls that point to a local PHP file. Why PHP? I have tons of security-tested approaches in a simple PHP-based API that work great and don't need re-inventing.
I'm guessing I'm missing something easy, but so far I've had a wonky/hacky approach that works. Right now, I've got a PHP file in the /static
folder, and in nuxt.config.js
I have a proxy setup:
... other config stuff
axios: {
proxy: true
},
proxy: {
'/api': 'http://some-site.local/api.php'
}
... other config stuff
In order for the url above to resolve, I have a host entry setup via MAMP that resolves http://some-site.local
to the /static
directory in my Nuxt project.
So far, it works. But, it requires setting up MAMP to have the hosts
entry, and when it comes to npm run build
, this approach fails, because the build will take the PHP files from the /static
and put them the the docroot of /dist
, but that breaks the API proxy setup for Axios in nuxt.config.js
.
I really don't want to install some PHP package (I've seen that Laravel has one that works with Nuxt), because the aim is just to be able to have a couple PHP files within my Nuxt project instead of a full library. Anyone have any insight on what I'm missing to make this work better?
Upvotes: 0
Views: 2346
Reputation: 2873
Lets say there is already Node and PHP-CLI installed.
Create NUXT project:
npx create-nuxt-app my-app
Create file static/api/index.php
(lets say):
<?php
header('Content-type: application/json; charset=utf-8');
$rawPaylaod = file_get_contents('php://input');
try {
$payload = json_decode($rawPaylaod, true);
} catch (Exception $e) {
die(json_encode(['error' => 'Payload problem.']));
}
echo json_encode([
'echo' => $payload,
]);
Install dependencies
npm i -D concurrently
npm i @nuxtjs/axios @nuxtjs/proxy
Update config.nuxt.js
:
module.exports = {
...
modules: [
...
'@nuxtjs/axios',
'@nuxtjs/proxy',
],
...
proxy: {
'/api': {
target: 'http://localhost:8000',
pathRewrite: {
'^/api' : '/'
}
},
},
axios: {
baseURL: '/',
},
}
Update package.json
:
"dev": "concurrently -k \"cross-env NODE_ENV=development nodemon server/index.js --watch server\" \"php -S 0.0.0.0:8000 static/api/index.php\"",
And it's ready.
Now locally in development API will be available thanks to proxy and after deployment just under path.
Upvotes: 2