to be under different domain, why axios.post dont work - javascript

https://github.com/skyturkish/e_commerce_advance this is the repo
index.js
const express = require('express')
const bodyParser = require('body-parser')
const UserService = require('./services/user-service')
const app = express()
app.set('view engine', 'pug')
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.render('index')
})
app.get('/users/all', async (req, res) => {
const users = await UserService.findAll()
res.render('user', { users })
})
app.get('/users/:id', async (req, res) => {
const user = await UserService.find(req.params.id)
res.send(user)
})
app.post('/users', async (req, res) => {
const user = await UserService.add(req.body)
res.send(user)
})
app.delete('/users/:id', async (req, res) => {
const user = await UserService.del(req.params.id)
res.send(user)
})
app.listen(3000, () => {
console.log('Server listening')
})
When I try to add a new user under "http://localhost:3000/" or "http://localhost:3000/users/all", this works. But under http://localhost:3000/users/1 throw an error. I cant understand well, why this happens, how does being under a domain authorize and receive it.

The GET handlers for / and /users/all use res.render(), but the GET handler for /users/:id uses res.send() (so it doesn't render your template, which in turn loads the axios library).

Related

Trying to connect to prismic got " '[Link resolver error] Unknown type\n' "

So I'm running an app with nodejs + express, and trying to connect to the prismic API. keep getting " '[Link resolver error] Unknown type\n' ", I understand from the message it's something about my routes but I'm unsure how to fix it
prismic config
require('dotenv').config()
const fetch = require('node-fetch')
const prismic = require('#prismicio/client')
const repoName = process.env.PRISMIC_REPO_NAME
const accessToken = process.env.PRISMIC_ACCESS_TOKEN
const endpoint = prismic.getEndpoint(repoName)
const routes = [
{
type: 'page',
path: '/'
}
]
module.exports.client = prismic.createClient(endpoint, {
fetch,
accessToken,
routes
})
app.js
require('dotenv').config()
const path = require('path')
const express = require('express')
const prismicH = require('#prismicio/helpers')
const { client } = require('./config/prismicConfig.js')
const app = express()
const port = process.env.PORT || 3000
// template engine
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
// middleware
app.use((req, res, next) => {
res.locals.ctx = {
prismicH
}
next()
})
app.get('/', async (req, res) => {
const document = await client.getFirst()
res.render('page', { document })
})
app.get('/about', (req, res) => {
res.render('pages/about')
})
app.get('/collections', (req, res) => {
res.render('pages/collections')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
prismic documents
folder structure
Edit: i fixed the issue
the issue was I was trying to render page, instead of pages/home
app.get('/', async (req, res) => {
const document = await client.getFirst()
res.render('page', { document })
})
so i just edited the res.render to :
res.render('pages/home', { document })
The error is likely being thrown because the routes object is not structured correctly. It should be structured like this:
const routes = {
page: '/',
blog_post: '/blog/:uid'
}
module.exports.client = prismic.createClient(endpoint, {
fetch,
accessToken,
routes
})
I fixed the error,
app.get('/', async (req, res) => {
const document = await client.getFirst()
res.render('page', { document })
})
the mistake was the I'm trying to render page, instead of pages/home so i edited this line
res.render('pages/home', { document })

Express, function is only executed once

I'm recently doing tests with the venom-bot library for whatsapp, but when executing the "action" action in my browser, it only runs once, after that it doesn't send a message to any number! I can't find where I'm going wrong.
const express = require('express');
const venom = require('venom-bot');
const bodyParser = require('body-parser');
venom
.create({
session: 'randomsession', //name of session
multidevice: true // for version not multidevice use false.(default: true)
})
.then((client) => start(client))
.catch((erro) => {
console.log(erro);
});
async function start(client) {
const app = express();
const PORT = 3333;
app.use(bodyParser.json())
app.get("/enviarcode", async (req, res, next) => {
await client.sendText(req.query.number + "#c.us", req.query.message);
res.json(req.query);
})
app.listen(PORT, () => {
console.log(`Online on Port ${PORT}`)
})
}

How would I send data from a post route to a get route in node js

I want to send data for products from my post request
router.post("/addProduct",(req, res) => {
const {addName, addDescription, addPrice, addImg} = req.body;
console.log(`${addName} added, the price is ${addPrice}`)
})
into the get request
router.get("/addProduct",(req, res) => {
//console.log(`getting ${addName}, and the price is ${addPrice}`)
console.log(`getting the response ${addName}`)
})
i want to send the const {addName, addDescription, addPrice, addImg} = req.body; into the get request, but I haven't found a lot of info on how to do that
You can, but it's against the convention.
const express = require("express");
const app = express();
const router = express.Router();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(router);
router.get("/addProduct", (req, res) => {
const { addName } = req.body;
console.log(`getting the response ${addName}`);
return res.json(addName);
});
app.listen(3000, (req, res) => {
console.log("listening...");
});

req.body is empty, why?

I want to send some data to my MongoDB database, but in router.post my req.body is empty, if I use stuff that I put in my send function in User(req.body) instead of req.body data will be send to my MongoDB database correctly.
This is my router that I use, router.get work fine, it return database tables correctly on /api page:
const router = require("express").Router();
const User = require("./model/models");
const parser = require("body-parser").json();
router.get("/", async (req, res) => {
const data = await User.find({});
res.json(data);
});
router.post("/",parser,async (req, res) => {
console.log('1')
console.log(req.body)
console.log('2')
parser.v
await User(req.body).save();
res.json({"msg": "ok"});
});
module.exports = router
This is my index.js file code:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const parser = require("body-parser").json();
var path = require('path');
app.use(express.urlencoded(true));
app.use(express.json());
app.use(parser);
app.use('/',require("./routes/routes"))
app.use(express.static(__dirname +'/public'))
app.use("/api", require('./data/api'))
app.listen(5000,function(){
console.log('server is alive')
})
This is function that what I use to send data:
const btn1 = document.getElementById('btnEnter')
let Login = "123"
btn1.addEventListener('click' ,e=>{
send({newsTxT : "someTextHere",newsZag:"someZag",author:"SomeAuthor"})
})
const send = async(body) => {
let res = await fetch("/api", {
method: "post",
header: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(body)
});
let data = await res.json();
console.log(data)
}
The only weird thing I see is that you are using a json body-parser and also the express.json() both technically do the same, but body-parser is deprecated so it might be causing a bug.
Also you don't have to import it again in the routes, placing app.use(express.json()) at index.js will make it work for all endpoints/routes.
See how this refactor goes:
const router = require('express').Router()
const User = require('./model/models')
router.get('/', async (req, res) => {
const data = await User.find({})
res.json(data)
})
router.post('/', async (req, res) => {
console.log('1')
console.log(req.body)
console.log('2')
await User(req.body).save()
res.json({ 'msg': 'ok' })
})
module.exports = router
index.js
const express = require('express')
const app = express()
var path = require('path')
app.use(express.urlencoded(true))
app.use(express.json())
app.use('/', require('./routes/routes'))
app.use(express.static(__dirname + '/public'))
app.use('/api', require('./data/api'))
app.listen(5000, function () {
console.log('server is alive')
})
The following worked fine:
const express = require("express")
const app = express()
const router = express.Router()
router.use(express.json())
app.use(router)
router.post('/api/user', function(req, res) {
// ...
}
I see the difference may be using the: app.use(router)
Note that in the above code the statement:
router.use(express.json())
can be replaced with (using the body-parser):
const bodyParser = require('body-parser')
router.use(bodyParser.json())
This worked fine with express version 4.17.1, body-parser version 1.19.0 and NodeJS version 12.18.3

My backend route is not behaving as it should and not posting anything to MongoDB

I am trying to create a simple CRUD app. I was trying to set up the first backend route but I am stuck and can't figure out what is wrong with my code or what I am missing.
If I try to test the route with Insomnia, it doesn't return any error, but it targets the basic "/" route and returns the console.log('OK') instead of creating an item in MongoDB. Here is my code:
// app.js file
require("./db");
const express = require("express");
const app = express();
require("./config")(app);
const backoffice = require('./routes/backoffice');
app.use('/api/backoffice', backoffice);
app.use('/', (req, res) => {
res.send('OK')
});
module.exports = app;
// route file backoffice.js
const router = require("express").Router();
const Item = require("../models/Item");
router.post('/backoffice', (req, res, next) => {
console.log(req.body);
const {title, description} = req.body;
Item.create({
title,
description
})
.then(response => {
console.log(response)
res.status(200).json({message: 'New item added succesfully'})
})
.catch(err => res.json(err))
})
module.exports = router;

Categories