I need to access my backend API to send info from a contact form for an email, I deployed my app in a webhost called Kinghost and it gave me two urls the first is generically mywebaddr.com:port-number and the second is mywebaddr.com/site.
I have tried to use both addresses with the function route in the end just like I did in localhost, that in order to work I used http://localhost:4000/contact for example, but it didn't work...
this is my request:
const baseUrl = 'http://mywebsiteurl.com/contact'
const initialState = {
message: {
name: '',
email: '',
subject: '',
main: ''
},
}
export default class ContactUs extends Component {
state = { ...initialState }
reset = () =>{
this.setState({message: initialState.message})
}
send = () => {
const message = this.state.message
const url = baseUrl
console.log(message)
axios.post(url, message)
.then(this.reset())
.then(alert('Message successfully sent!'))
}
this is my index.js (backend)
const express = require('express')
const app = express()
const consign = require('consign')
const port = 4005
consign()
.then('./config/middlewares.js')
.then('./api')
.then('./config/routes.js')
.into(app)
app.listen(port, () => {
console.log(port)
})
my middlewares.js contains cors
const bodyParser = require('body-parser')
const cors = require('cors')
module.exports = app => {
app.use(bodyParser.json())
app.use(cors())
}
Actually, I don't think it's because of my code itself once I can execute everything perfectly in localhost, but somehow I can't get through with the correct URL
I'm new to node and I can't guess what am I doing wrongly, so if someone can help me I'd be really thankful :)
This is not a question for stack-overflow as your issue is not with the application but is with your network.
Anyhow, your API application is running on port 4005. Make sure the port is open with your hosting provider. while your at it make sure your port 4000 is open as well.
after you confirm your firewall settings ill update my answer if your still facing issues.
Related
I am trying to upload my NodeJS project on Heroku. The project is a multiplayer game, locally the code works for me and both players enter the same map. But, in Heroku I don't get both players on the same map.
I leave the NODEJS code
const express = require("express")
const cors = require("cors")
const app = express()
app.use(express.static('public'))
app.use(cors())
app.use(express.json())
const jugadores = []
const PORT = process.env.PORT || 8080
class Jugador {
constructor(id) {
this.id = id
}
asignarMokepon(mokepon) {
this.mokepon = mokepon
}
actualizarPosicion(x, y) {
this.x = x
this.y = y
}
asignarAtaques(ataques) {
this.ataques = ataques
}
}
class Mokepon {
constructor(nombre) {
this.nombre = nombre
}
}
app.get("/unirse", (req, res) => {
const id = `${Math.random()}`
const jugador = new Jugador(id)
jugadores.push(jugador)
res.setHeader("Access-Control-Allow-Origin", "*")
res.send(id)
})
app.post("/mokepon/:jugadorId", (req, res) => {
const jugadorId = req.params.jugadorId || ""
const nombre = req.body.mokepon || ""
const mokepon = new Mokepon(nombre)
const jugadorIndex = jugadores.findIndex((jugador) => jugadorId === jugador.id)
if (jugadorIndex >= 0) {
jugadores[jugadorIndex].asignarMokepon(mokepon)
}
console.log(jugadores)
console.log(jugadorId)
res.end()
})
app.listen(PORT, () => {
console.log("Servidor funcionando", PORT)
})
I leave a small part of the code here because it is not possible to publish so much code. But I leave a link to the repository on GitHub
Link of the page hosted on Heroku:https://proyecto-mokepon.herokuapp.com/
Code link on GitHub: https://github.com/IamMatiasBazan/proyecto-mokepon
Locally it generates the random number for each player
enter image description here
Deployed in Heroku I see this:
enter image description here
The requests you are sending is pointed to localhost in your js file (multiple places, but this is one). Here you should consider changing it to be the heroku domain or just /mokepon/${jugadorId}/ataques (or something else).
It also looks like the app is sending a new request every 50ms, even if nothing happens. In this case I would then suggest you to look into socket.io to prevent the application to send useless request everytime.
I have the following in my Create React App as per https://create-react-app.dev/docs/proxying-api-requests-in-development/
src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
This works fine and sends all requests to my nodejs app running on port 5000. However I wish to intercept the request somehow and rewrite the path into a url query string format.
I have json-server running on the nodejs server which needs the requests to be formatted differtently, using this type of format /api/cheeses?cheeseno=12
For example
'/api/cheese/12' => `/api/cheeses?cheeseno=12`
I have come across pathRewrite and router on this page https://www.npmjs.com/package/http-proxy-middleware but I have no idea how to map them over.
Later on as I get mor advanced, I will need to map nested path routes to url queries.
So
/location/{locationId}/aisle/{aisleid}/cheeses => /api/cheeses?locationId=12&aisleid=123`
Thanks
const { createProxyMiddleware } = require('http-proxy-middleware');
const rewriteFn = function (path, req) {
return path.replace('/api/foo', '/api/bar');
};
const options = {
target: 'http://localhost:3000',
pathRewrite: rewriteFn,
};
const apiProxy = createProxyMiddleware('/api', options);
rewriteFn is the key
https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md#custom-rewrite-function
I have a Heroku app with Cloudflare and I try to display a different version according to the localization of the client.
It works well in developpment but it's not the case in production (the /en is always displayed, not the /fr).
I use the express-ip npm package.
The code:
const express = require('express');
const router = express.Router();
const expressip = require("express-ip");
router.use(expressip().getIpInfoMiddleware);
router.get("/", function ipFrance(req, res) {
const ipInfo = req.ipInfo;
const ipInfoRegion = req.ipInfo.region;
const ipInfoCountry = req.ipInfo.country;
//var message = `Hey, you are browsing from ${ipInfoRegion}, ${ipInfoCountry}`;
if(ipInfoCountry == "FR" || ipInfoRegion == "Wallonia") {
res.redirect("/fr");
} else {
res.redirect("/en");
}
});
module.exports = router;
Don't offer translations based on IP address. There's an HTTP header for that, and an express API method req.acceptsLanguages() which uses that header:
router.get("/", function (req, res) {
if (req.acceptsLanguages("fr")) {
res.redirect("/fr");
} else {
res.redirect("/en");
}
});
Some French-native people may like browsing in English, and other parts of the world may prefer to browse in French. Let them make that decision, don't make it for them.
I keep getting this GET /socket.io/?EIO=3&transport=polling&t=MfRfeJD 404 4.438 ms - 149 error and I don't know where it's coming from.
I'm trying to integrate a live chat into my application using react, socket.io and express and I keep getting this not found error with the sockets. I'm not sure if the problem is on the client or server side. It appears to be trying to continuously poll the server, but is getting 404's back. That sounds like socket.io isn't running, but it all looks okay to me. It may also have something to do with paths, but I don't really know. I've tried adding different route to the io like "http://localhost:5000/" but still it still can't find the socket.
I get the page to show up and when I click send the message shows up but I can't get the sockets to connect.
In app.js
const express = require('express');
const http = require('http')
const bodyParser = require('body-parser')
const socketIo = require('socket.io')
var app = express();
const server = http.createServer(app)
const io = socketIo(server)
var PORT = process.env.PORT || 5000;
app.post('/', (req, res) => {
const { Body, From} = req.body
const message = {
body: Body,
from: From.slice(8),
}
io.emit('message', message)
res.send(`
<Response>
<Message>Thanks for texting!</Message>
</Response>
`)
})
io.on('connection', socket => {
socket.on('message', body => {
socket.broadcast.emit('message', {
body,
from: socket.id.slice(8)
})
})
})
server.listen(PORT);
In Chat.js
import React from "react";
import io from "socket.io-client";
class Chat extends React.Component {
constructor (props) {
super(props)
this.state = { messages: [] }
}
componentDidMount () {
this.socket = io('http://localhost:5000/')
this.socket.on('message', message => {
this.setState({ messages: [message, ...this.state.messages] })
})
}
handleSubmit = event => {
const body = event.target.value
if (event.keyCode === 13 && body) {
const message = {
body,
from: 'Me'
}
this.setState({ messages: [message, ...this.state.messages] })
this.socket.emit('message', body)
event.target.value = ''
}
}
render () {
const messages = this.state.messages.map((message, index) => {
return <li key={index}><b>{message.from}:</b>{message.body} </li>
})
return (
<div>
<h1>Admin Chat</h1>
<input type='text' placeholder='Enter a message...' onKeyUp={this.handleSubmit} />
{messages}
</div>
)
}
}
export default Chat;
404 is clearly saying no such page
149 will be the line number of the failure, your importing other code so it can be on any of the other code that the line 149 exists
i do see a maybe in app.js and the path
"app.post('/', (req, res) => {" Refers to an absolute path
try changing "http://localhost:5000/"
to "http://localhost:5000" or "http://localhost/:5000"
it looks like the "/" on the end puts the 5000 in the path not the port
--- EDIT --- on closer look at GET /socket.io/?EIO=3&transport=polling&t=MfRfeJD
if chat.js is running on the client and connecting to http://localhost:5000 than;
http://localhost/socket.io/?EIO=3&transport=polling&t=MfRfeJD would be the attempted connection
it looks like client is trying to connect back to itself.
how do you have the client / server setup?
if they are separate machines this would be looking for a non existing url.
either way is happening in the socket.io library.
I've got a problem with sending e-mails from my (let's say) contact form. It works brilliant when I'm connected to only two networks: my mobile hotspot and at my office. When I'm connected to any other network with internet access, it doesn't work (there are no errors, but no e-mails as well :( ... )
At first time I used SendGrid and I thought that the problem is within SendGrid. I even contacted with SendGrid support team and I was said, that code is correct and my settings are also allright.
In the next step I tried a Nodemailer - unfortunatelly the same effect...
Need a clue, what might be a problem?
Below is my code responsible for creating and sending e-mail request:
Here's a code
const express = require("express");
const cors = require("cors");
const sgMail = require("#sendgrid/mail");
require("dotenv").config();
const API_KEY = process.env.REACT_APP_SG_MAIL_API_KEY;
sgMail.setApiKey(API_KEY);
const app = express();
app.use(cors());
app.get("/", (req, res) => {
res.send("Hello");
});
app.get("/send-email", (req, res) => {
const { recipient, sender, topic, html, senderName } = req.query;
let subject = topic + senderName;
const msg = {
to: recipient,
from: sender,
subject: subject,
html: html
};
sgMail.send(msg).then();
});
app.listen(4005, () => {
console.log("Server 4005 is listening");
});
As I said before - it works perfect with two specific networks mentioned above.
EDIT:
Here is my fetch request:
fetch(
`${window.location}/send-email?recipient=${email.recipient}&sender=${
email.sender
}&topic=${email.subject}&html=${myhtml}&senderName=${senderName}`,
{ mode: "no-cors" }
).catch(err => console.log(err));