Cannot POST /api/block - node.js

I am testing a GET & POST methods using ThunderClient extension and NodeJs, but I am unable to post the data ...it is showing cannot post data followed by relative path , (Get method is working perfectly) :
Here is my Index.js code:
const express = require('express')
const bodyParser = require('body-parser');
const Blockchain = require('./Blockchain');
const blockchain = new Blockchain();
const app = express();
app.use(bodyParser.json());
app.get('/api/block' , (req,res)=>{
res.json(blockchain);
})
app.post('/api/mine' , (req,res)=>{
const {data} = req.body;
blockchain.addBlock({data});
res.redirect('/api/block');
})
const PORT = 3000;
app.listen(PORT , ()=>{
console.log("app is listening");
})

The default status code of the redirect is 302 which doesn't change
the request method.
Instead it stays as POST
To redirect as a GET method, you have to use 303 status code.
Also see
res.redirect
Temporary redirects

Related

I can't render images from an API in my fronted application

I'm building an appplication using react at the front and express at the back in order to avoid cors issues. From the back I get the Json of my API from "Zoho Creator". Here an example.
As you can see I get a Json object, but in the image value, the URL appear without https://zoho.creator.eu... and when I try to request them from my frontend I can't render them. and if I add https://... at the beginning manually I get an error 401. I also tried to add the https route from the backend but is the same thing.
Here my backend using express
PD: I'm a rookie I know, please don't judge me.
const express = require("express")
const app = express()
const fetch = require("node-fetch")
const bodyParser = require("body-parser");
const cors = require("cors")
const PORT = process.env.PORT || 4000;
app.use(bodyParser.json());
const urlPost = ("https://accounts.zoho.eu/oauth/v2/token?refresh_token=1000.3dbdad6937dc0800c4dcc662cd14d173.86efb18e337989bebb3ff4c05582c94c&client_id=1000.NQL17JHK3Y62Y178TO0E3FQC6MBQJV&client_secret=5d04ad135862e7313377484af55efa1f41c1f49a39&grant_type=refresh_token")
const urlGet = "https://creator.zoho.eu/api/v2/hostienda1/Product-Catalog/report/Product_Details";
app.use(cors())
app.get
const peticion = fetch(urlPost,{
method: 'POST',
redirect: 'follow'
});
peticion
.then((ans)=>{return ans.json()})
.then((resp)=>{
const reslt = resp.access_token;
return app.get("*", async (req,res)=>{
const response = await fetch(urlGet,{
method: "GET",
headers:{
'Authorization':`Zoho-oauthtoken ${reslt}`,
}})
const result = await response.json()
const test = result.data
test.map(function(product){
if (true){
product.Product_Images[0] = "https://creator.zoho.eu" + product.Product_Images[0].display_value
return product.Product_Images[0]
}
})
res.json(test)
})
})
app.listen(PORT, () => {console.log(`Listening on port ${PORT}`)})`
I hope to render my images from my frontend app.
I assume that the download link for the image also requires authentication, in other words, the download requires a request like
GET https://creator.zoho.eu/api/v2/hostienda1/Product-Catalog/report/Product_Details/...jpg
Authorization: Zoho-oauthtoken ...
Such a request cannot be made your frontend, because it does not know the Zoho-oauthtoken.
This means that you must make this request in your backend. Rewrite your middleware so that it retrieves the download link for one image only (currently you return test, which contains many images). Then use the following code to access the image at that download link and return it to the frontend:
var img = await fetch("https://creator.zoho.eu/api/v2/...", // the download link
{headers: {authorization: `Zoho-oauthtoken ${reslt}`}}
);
res.set("content-type", img.headers.get("content-type"));
stream.Readable.fromWeb(img.body).pipe(res);

cookie are not set in browser when I am use the node as backend

Cookies are not set in browser. I am use the node as backend. I am try to search problem some person tell that's cookies will not setting because of I am using react as front and node as backed both are run on same virtual server that is localhost. That why it happen.
this is my code please help.
User.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const RegisterModel = require("../Model/RegisterModel")
const signIn = async (req,res)=>{
try {
const data = await RegisterModel.findOne({Email:req.body.email})
const passwordMatch = await bcrypt.compare(req.body.password,data.Password)
const token = await jwt.sign({Email : data.Email}, process.env.SECRET)
if(!data) return res.status(404).json({islogin:false, message: "User doesn't exist" })
if(!passwordMatch) return res.status(400).json({islogin:false,message: "Incorrect Password"})
if(passwordMatch){
res.cookie('newToken',token, { maxAge: 900000, httpOnly: false});
res.status(200).send({id:data._id,email:data.Email,name:data.Name,islogin:true,token:token})
}
} catch (error) {
res.status(404).json({islogin:false,message:"User doesn't exist"})
console.log(error)
}
}
module.exports = {signIn,signUp};
app.js
const express = require('express');
var cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser())
const dotenv = require('dotenv');
dotenv.config()
var cors = require('cors')
const PORT = process.env.PORT ;
const router = require("./Router/Router")
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended:false}));
app.use(router);
require("./Connection/Connection")
app.listen(PORT,()=>{
console.log(`Listen at Port ${PORT}` )
})
for set credentials data into browser it is necessary to run both side on same domain backend should be run on localhost or 127.0.0.1 and frontend should be run on localhost or 127.0.0.1 respectively.
or
backend and frontend run on =localhost or
backend and frontend run on =127.0.0.1
if you are not sure then issue error's show on console. here
browser suggest you error regarding cookies.
also set cors policy on backend side like =
cors({origin:"http:localhost:frontendPORT", credentials:true})
frontend side on http request, must be set with credentials= true
this method work for me after spending 4 days.

Why ECONNRESET error is coming in POSTMAN while making a NODEJS request

I have written a simple request response code in NODEJS but there is no response in return of the request is there .
The code for my app.js(Server file) is
const express = require('express');
const cors = require('cors')
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors);
app.use("/api",paymentroute);
app.listen(3100,()=>{
console.log(`listening to port 3100`);
})
The code for my req and res is
const express = require('express');
const router = express.Router();
// const { checkout } = require('../controllers/paymentController');
router.post("/checkout",(req,res) => {
console.log("this function is called ")
return res.json({success:"true"})
});
module.exports = router;
Even the console.log inside the res function is not working.
Just change app.use(cors); to app.use(cors());
const express = require('express');
const cors = require('cors');
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors());
app.use('/api', paymentroute);
app.listen(3100, () => {
console.log(`listening to port 3100`);
});
I think it is a connection-related issue often related to a networking issue caused by a Virtual Private Network (VPN) that in some cases is required by some API services or, in other cases, prevents you to reach an API service.
The issue seems to be a combo of having the no-cache header enabled and a request URL length over 64 characters. If the issue persists after doing this solution then try to upgrade to the latest version of Postman.

Problem with ssl comuniction with post request

Hey, I built ssl communication with self certificate. The connection is working, but when I trying to deliver data on the client side with post request in postman or my android client, the body of the request in the server side is empty.
Here is my nodejs server code below,thankes for help.
const express = require('express')
const https = require('https')
const path = require('path')
const fs = require('fs')
const app = express()
app.use(express.json())
app.post('/',(req,res,next)=>
{
console.log("we got new connection")
var data =req.body
res.send(data)
})
const ssl_server = https.createServer(
{
key:fs.readFileSync(path.join(__dirname,'cert','key.pem')),
cert:fs.readFileSync(path.join(__dirname,'cert','cert.pem'))
},app)
ssl_server.listen(3443,console.log("SSl server is online!"))
You're reading the response body. You should look at the request.
In any case, there won't probably be much reasonable data to read unless you parse the POST payload somehow; I'd recommend the Express library rather than raw Node.js HTTP bits if you don't want to do that yourself.
here is my answer for my question,like AKS said, you need to parse the post request, i add bodyparser to my code and it worked.
const express = require('express')
const https = require('https')
const path = require('path')
const fs = require('fs')
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.urlencoded({ extended: true })) // <==== parse request body as JSON
app.post('/',(req,res,next)=>
{
console.log("we got new connection")
var data =req.body
res.send(data)
})
const ssl_server = https.createServer(
{
key:fs.readFileSync(path.join(__dirname,'cert','key.pem')),
cert:fs.readFileSync(path.join(__dirname,'cert','cert.pem'))
},app)
ssl_server.listen(3443,console.log("SSl server is online!"))

node and express error "cannot GET /" even after I included app.get() in my server.js

I am trying to start my project via launching server.js but I am getting error:"cannot GET /"
even after I made an app.get() route in my server.js
I am using also "body-parser" as a middleware, and "cors"
server.js:
// Setup empty JS object to act as endpoint for all routes
const projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('views'));
const port = 8080;
app.use(express.static('dist'));
// Setup Server
const server=app.listen(port, ()=>{console.log(`running on localhost: ${port}`)});
app.get('/all', sendData);
function sendData (request, response) {
response.send(projectData);
};
// TODO-ROUTES!
app.post('/add', Info);
function Info(req, res) {
projectData['date'] = req.body.date;
projectData['temp'] = req.body.temp;
projectData['content'] = req.body.content;
res.send(projectData);
}
module.exports = server;
I made a POST request to /add and it works. Then I call GET /all and also work. The error cannot GET / is because you are requesting an endpoint that not exists.
Just add a dummy data to your Fn() if you want to see some output on GET request wihtout making any post request
Here is my solution
app.get('/', (req, res) => {
res.redirect('/all');
})
we need this because you do not have any root URL set, so we set the root URL to redirect to /all
2nd step then we add a dummy data in the projectData
var projectData = {
date = new Date().getDate();,
temp = 10,
content="This is Test Content"
}
This way when you call 'http://localhost:8080/' you shall get redirected to http://localhost:8080/all and instead of empty {} you shall see the dummy data.

Resources