Hi i need to do a webapp with user registration and I would like to try the script locally. I do all site with Vue Axios and I need to implement jwt. Can someone let me how i can start locally server for test this script?
import axios from 'axios'
export default {
name: 'Register',
data() {
return {
email: '',
password: '',
nome: '',
cognome: '',
data: '',
telefono: '',
risiedi: '',
cap: '',
provincia: '',
citta: '',
privacy: false
}
},
methods: {
handleSubmit() {
const data = {
email: this.email,
password: this.password,
nome: this.nome,
cognome: this.cognome,
data: this.data,
telefono: this.telefono,
risiedi: this.risiedi,
cap: this.cap,
provincia: this.provincia,
citta: this.citta,
privacy: this.privacy
};
axios.post('http://localhost:8000', data)
.then(
res => {
console.log(res)
}
).catch(
err => {
console.log(err)
}
)
}
}
}
CodePudding user response:
To install a simple Node.js server using Express.js, first ensure that you have express-generator installed on your global npm. You can run the command below to install
npm install -g express-generator // may require (sudo) in some instances
Go to your desired project directory (e.g. cd backend), and make sure it is empty
.
├── frontend
├── backend
Then run the command
npx express-generator
Install the dependencies
npm install
Install cors
npm install cors
Set up cors (Cross Origin Resource Sharing) by opening app.js
// paste this at the top of the file
const cors = require('cors')
// then paste this somewhere after var app = express();
const corsOptions = {
origin: 'http://localhost:<Your_Frontend_Port>',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
/* Enable CORS in the app */
app.use(cors(corsOptions))
Spin your server by running
npm start
You can now access your server by accessing
http://localhost:3000 // this is the default port
You can change the server port by defining a .env file and declaring PORT=<Your_preferred_port> and then running npm install dotenv before pasting require('dotenv').config() at the top of bin/www
You can modify the routes by access routes/index.js or routes/users.js. For example, to return JSON to the client, use response.json({ yourKey: 'Your content' }) or res.send({ name: 'MyName' }). Both .json and .send are almost identical but we'll leave it here, for now.
Let us try an example route. Go to routes/index.js and add a route
/* GET name page */
router.get('/test', function(req, res, next) {
res.json({ testKey: 'Test content' })
});
On the frontend, do something like
axios.get('http://localhost:3000/test')
.then(res => { console.log(res) })
.catch(err => { console.log(err) })
To make your server reload immediately after making changes, install nodemon on the server
npm install nodemon -D
Go to the package.json and replace "start": "node ./bin/www" with "start": "nodemon ./bin/www"
Stop the server and run npm start once again
For more details, check the express documentation
