Nextjs custom server.js proxy to api - javascript

im trying to proxy to backend api which is running on port 5000. i have created a custom server.js file for my nextjs app. but its not working im getting 'Application error: a client-side exception has occurred (see the browser console for more information)' error. and when i check the console, indeed the data is not fetching from backend.
server.js:
const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require("http-proxy-middleware")
const port = 3000
const app = next({})
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.use('/api/products', createProxyMiddleware({ target:
'http://198.51.100.255:5000', changeOrigin: true }))
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(port, () => {
console.log(`app running on port ${port}`)
})
})

Related

trying to hide api but backend gives me error

image of the error I am trying to build nft search app that when you give adress it finds the nfts that a wallet has. but i am using alchemy and don't want to expose api key. Don't know backend, using next.js.
my backend code:
const express = require("express");
const axios = require("axios");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/api", (req, res) => {
const apiKey = process.env.API_KEY;
const owner = req.query.owner;
const baseURL = `https://eth-mainnet.g.alchemy.com/nft/v2/${apiKey}/getNFTs/`;
const fetchURL = `${baseURL}?owner=${owner}`;
axios
.get(fetchURL)
.then((response) => {
res.json(response.data);
})
.catch((error) => {
res.json({ error: error.message });
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
my frontend
const fetchNFTs = async () => {
const response = await fetch(`/api?${wallet}`);
const nfts = await response.json();
setNFTs(nfts);
};
I tried chat gpt, serverless function but I failed to achieve results
Is this a separate Express server? By default Next.js runs on port 3000, and that's why you're making a GET to localhost:3000. But if your Next.js server is started, your custom Express server would pick a different port because the 3000 is going to be taken. So your const response = await fetch('/api?${wallet}'); will result in a 404 because there's no such route in your Next.js app.
You could move your function into a Next.js API handler if you want your backend and frontend to live under the same port. Also you wouldn't need to manually create the express server and take care of the dotenv since Next.js is going to take care of that for you.

I want to build my own webhook dispatch server using node js?

I am trying to build a webhook server using node js. If any user sets their server URL as a hook using API provided by me, then my webhook server should respond to that user server.
I got this idea from the Facebook Messenger Chatbot application which uses the same approach.
Server 1 - My Server
const express = require("express");
const axios = require("axios");
const app = express();
const PORT = 3000;
/* Set Middleware to Express App */
app.use(express.json());
// Routes
app.post("/handle-webhooks", (req, res) => {
const body = {"id": "1", "message": "hello"};
const headers = {
'Content-Type': "application/json",
}
const clientWebhookUrl = "http://localhost:8093/webhook2" // This will be different for each client
axios.post(clientWebhookUrl, body, {headers})
return res.sendStatus(200);
})
app.post("/set-webhook", (req,res) => {
const clientWebhookUrl = req.url;
// This URL will be saved to database
return res.sendStatus(200)
}
/* Listen Server */
app.listen(PORT, () => {
console.log(`App is listening on port ${PORT}.`);
})
Server 2 - My Client 1 Server
Using postman, the Client will make a post request to http://localhost:3000/set-webhook and set the webhook2 endpoint of his web server as a webhook URL to receive a response from my server.
const express = require("express");
const axios = require("axios");
const app = express();
const PORT = 8093;
/* Set Middleware to Express App */
app.use(express.json());
// Routes
app.post("/webhook2", (req, res) => {
const body = req.body; // receives {"id": "1", "message": "hello"}
return res.status(200).send(body);
})
/* Listen Server */
app.listen(PORT, () => {
console.log(`App is listening on port ${PORT}.`);
})
Is the above approach is correct for doing this task? or do I need to add more complex code for this?
Thanks.

Getting error 405 when sending request on express route in next js

I create routes on Express js in Next js. When i deployed on hosting and sent request on route i getting error 405, but when i do same on localhost everything all right.
I cant understand that is this?
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3000
const dev = process.env.NODE_ENV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
nextApp.prepare().then(() => {
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const apiRoutes = require("./routes");
app.use('/api', apiRoutes)
app.get('*', (req,res) => {
console.log('asdfasdfasdfd')
return handle(req,res)
})
app.listen(PORT, err => {
if (err) throw err;
console.log(`ready at http://localhost:${PORT}`)
})
})
I think your express config has problem.
your express server must be like this:
const express = require('express')
const next = require('next')
const handler = routes.getRequestHandler(app)
const app = next({ dir: '.', dev })
app.prepare().then(() => {
const server = express()
server.post('/api', (req, res) => {
handler(req, res, req.url)
)
server.get('*', (req, res) => {
handler(req, res, req.url)
})
}
check the code for server.get and server.post or other http methods.
Error 405 tells that the method is not allowed.
Vercel can't use custom server with next js
https://github.com/vercel/next.js/discussions/13306

node server not returning response for this particular data set

I aa running a node server returning data for fetchdata api.
const express = require('express')
const app = express()
const port = 3000
const z = { 'a': 'tobi' };
app.get('/fetchdata', function (req, res) {
res.json(z);
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
In second scenario i am running a node server consuming the api provided by first node.
const express = require('express')
const app = express()
const port = 3001
app.get('/', (req, res) => res.send(`
<html>
<body>Hello user!!</body>
<script>
fetch('http://localhost:3000/fetchdata', {mode: 'no-cors'})
.then(res => res.json())
.then(res => console.log(res))
</script>
</html>
`));
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I am not able to get any response in the second case. Api displays blank response. If i am keeping z = [{ 'a': 'tobi' }]; it works fine. It only fails for previous value of z.

How do I transfer this local server API to a web API to deploy my app in heroku?

I have these code for a Chat App and it is only working in Local Server
I have already tried the following. Calling io() without any path arguments.
// Client Side Code
socket = io();
socket.connect({ query: `username=${props.username}` })
The above didnt work. The app runs but does not show other user's messages.
// Client Side Code
socket = io('http://myherokuapp:3001', { query:
`username=${props.username}` }).connect();
Neither did the above code work. The app crashed on this one.
Here is my actual source code:
// Server Side Code
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
const http = require("http");
const cors = require("cors");
const io = require("socket.io");
const server = http.createServer(app);
const socketIo = io(server);
app.use(cors());
app.get('/messages', (req, res) => {
res.sendFile(path.resolve('./public/index.html'));
});
socketIo.on('connection', socket => {
const username = socket.handshake.query.username;
console.log(`${username} connected`);
socket.on('client:message', data => {
console.log(`${data.username}: ${data.message}`);
socket.broadcast.emit('server:message', data);
});
socket.on('disconnect', () => {
console.log(`${username} disconnected`);
});
});
server.listen(PORT, () => {
console.log(`🌎 ==> API server now on port ${PORT}!`);
});
// Client Side Code
socket = io('http://localhost:3001', { query:
`username=${props.username}` }).connect();
socket.on('server:message', message => {
addMessage(message);
});
socket.emit('client:message', messageObject);
addMessage(messageObject);
I expect the chat app to be working same as it does in localhost.

Categories