I need to send request from server to same server with axios as PUT method exmp.
await axios({
url: `http://localhost:4000${url}`,
method: requestType,
headers: { ...req.headers, 'Content-Type': 'multipart/form-data' },
data,
}).catch((err) => console.log('error :>> ', err))
the problem is that I am not getting any error and request is not sent. After while I receive Timeout error
You should check and ensure $url, requestType and ...req.headers are correct and that you can curl that endpoint. And why not ask your question with their correct values instead of using variables whose values we don't know. In any case, here's something working in express
const axios = require('axios')
const express = require('express')
const app = express()
const port = 4000
app.get('/', (req, res) => {
res.send('Hello World!')
})
const url = `http://localhost:${port}`;
app.listen(port, () => {
console.log(`Example app listening at ${url}`)
})
axios({
url: url,
method: 'get', // tried with post and put too
})
.then(res => {
console.log(res.data)
})
.catch((err) => console.log('error :>> ', err))
Related
I want to send values from react to node. I am using fetch but I am not getting. Here's the code:
React Code:
const values = {email,pass}
const data = {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(values),
}
fetch('http://localhost:8000/', data)
.then(res => res.json())
.then(data => console.log(data))
Node Code:
const express = require("express")
const cors = require('cors')
const app = express()
app.use(
cors({
origin: '*'
})
)
app.listen(8000, 'localhost')
app.post('/' , ( req, res ) => {
console.log(req.body)
} )
When I am visiting to this http://localhost:8000/
i am getting an error
Cannot GET /
use json body parser:
app.use(express.json());
You need express to use json body parser:
app.use(express.json());
Additionally you are not sending any response from your Node Server to the client,
try something like this this:
app.post('/' , ( req, res ) => {
console.log(req.body)
const data = JSON.stringify(req.body)
console.log(data)
res.status(200).json({data: data});
})
I hosted website on two different platforms like Firebase and Heroku
I Have some issues with that
Firstly, It showing cors errors when I post data from firebase hosted URL to the server which is hosted on Heroku
Then after resolving cors errors data couldn't from the server it showing undefined in console
Here is my server-side code which is hosted on Heroku
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 3000
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.use(express.json({limit:'1mb'}))
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'https://sample-377b8.web.app');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With,content-type,Accept,Authorization',);
res.header('Access-Control-Allow-Credentials', true);
if(req.method=="OPTIONS"){
res.header('Access-Control-Allow-Methods','PUT,POST,DELETE,PATCH')
return res.status(200).json({})
}
// Pass to next layer of middleware
next();
});
let data;
app.get('/',(req,res)=>{
res.send("hello world")
})
app.post('/',(req,res)=>{
data = req.body
console.log(data)
res.status(200).json({
"success":"200 response",
"res":"You are now just talked with server"
})
})
app.listen(PORT, () => console.log(`Listening on ${ PORT }`))
This is my client side code
document.getElementById('send').addEventListener('click',async()=>{
let data = {lat,lon}
await fetch('https://demoserver-app.herokuapp.com/',{mode:"no-cors"},{
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then( async (dat) =>{
console.log(res.json())
}).then(res =>{
console.log(res)
})
})
It is giving the error on a console like
console error image
Headers information in the network tab
Header information of request image
I hope I can help you,
one issue that I see that can make this kind of output
is that you console.log(res) but .then referring to (dat)
And I don''t think you need async inside .then(it's already async function)
try this:
document.getElementById('send').addEventListener('click',async()=>{
let data = {lat,lon}
await fetch('https://demoserver-app.herokuapp.com/',{mode:"no-cors"},{
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then( data =>{
data.json()
}).then(res =>{
console.log(res)
})
})
ok, so for the server side:
1)you need to destructure data from req.body, what you made is just adjust req.body to data bar.(see my solution)
2) for the post method you need to make a directory and not try it in the root directory.
try this code you will see the response you want
server:
app.post('/getmessage', (req,res) => {
const {data} = req.body;
console.log(data);
res.status(200).json({
"success":"200 response",
"res":"You are now just talked with server"
})
})
client:
fetch('http://localhost:3000/getmessage', {
method : 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
data:"this is massage from client"
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
Im working on simple app that allows you to register new user. I managed to create fetch POST request and catch it with express app.post method. It works but the value that req.body is retruning is not plain object but something more that I want.
It's literally returning something like this : { '{"login":"fff","password":"sss"}': '' }
But I want it to be just sth like this: {"login":"fff","password":"sss"}
Here is my client side code
function eventListener() {
const formSubmit = document.querySelector('.register-form');
const newUser = new Register();
formSubmit.addEventListener('submit', (e) => {
e.preventDefault();
newUser.checkInputs();
const form = e.target;
const formData = new FormData(form)
const userData = {
login: formData.get('login'),
password: formData.get('password'),
}
console.log(userData);
fetch('/register', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: JSON.stringify(userData)
})
.then(response => {
console.log(response);
})
})
}
document.addEventListener('DOMContentLoaded', eventListener)
And here is server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json())
app.use(express.urlencoded({
extended: true
}))
app.use(express.static('static'))
app.post('/register', (req, res) => {
console.log('ok');
console.log(req.body);
res.end();
})
app.listen(process.env.PORT || 5000, () => {
console.log('running...');
})
Don't lie to the server:
'Content-Type': 'application/x-www-form-urlencoded'
You are sending JSON.
By telling the server you are NOT sending JSON, you are confusing it.
It is trying to parse it as application/x-www-form-urlencoded
Tell it you are sending JSON:
'Content-Type': 'application/json'
MRE -> node-server : react app
When I send a POST request using Postman, I get the expected result. This is the request that I am sending using Postman
and test sent gets printed to the console of my node server
If I send a request from my react form however, test sent does not print to the console, but the catch block of my fetch request get's executed and err is printed to the console of my react app, followed by {}.
I would like to know why my POST request is not working and is not getting received by the server
Below is the function that I call when someone clicks the submission button of my form created in react
Function called on form submission
nodeUrl = 'https://localhost:6060?'
const submitData = async () => {
fetch(nodeUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({'test': 'test'})
}).then((res) => {
alert('then')
}).catch((err) => {
alert('err')
alert(JSON.stringify(err))
})
}
}
This is the server that I run using node server.js
server.js
server.post('/', function(req, res) {
console.log('test sent')
mailer.messages().send(req.body)
.then((mes) => {
console.log(mes)
res.json({ message: 'Thanks for your message. Our service team has been notified and will get back to you shortly.' })
}).catch(err => {
console.log(err)
res.json(err);
})
});
The majour issue here is due to CORS. CORS support can be used to overcome this. Just keep in mind to have this only for development mode(see below codes).
But, as per the Postman's snapshot and provided GitHub repositories, the request from Front-end should be of multipart/form-data type. Thus, the Front-end code would look like this
const nodeUrl = "http://localhost:6060/";
const submitData = async () => {
// create a FormData object
const formData = new FormData();
formData.append('form', 'example#email.com');
formData.append('to', 'example#email.com');
// this auto adds 'multipart/form-data' + HASH header in the request
fetch(nodeUrl, {
method: "POST",
body: formData
})
.then(res => {
console.log(res);
}).catch(err => {
console.log('Error -', err);
});
};
To handle multipart/form-data request in the ExpressJS, you need a plugin Multer.
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer'); // for 'multipart' type request
const server = express();
const upload = multer();
// allow CORS requests in development mode
if (process.env.NODE_ENV === 'development') {
// Server run command - "NODE_ENV=development node server.js"
const cors = require('cors');
server.use(cors());
}
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: true}));
// using Multer middleware form extracting 'FormData' payload
server.post('/', upload.none(), function(req, res) {
console.log('Received body', req.body);
... // other codes
});
Strategy 2(plain JSON) -
If that 'multipart/form-data' strategy was unintentional and you just want to send simple JSON, use below codes -
In Front-end, trigger API request as -
fetch(nodeUrl, {
method: "POST",
headers: {
'Content-Type': 'application/json', // this needs to be defined
},
body: JSON.stringify({ from: 'some#email.com', to: 'other#email.com' })
})
In server, just ignore codes related to Multer and only keep your API as -
server.post('/', function(req, res) {
console.log('Received body', req.body);
... // other codes
});
I ended up using a better fetch request, which was put together for me by selecting code -> Javascript Fetch in Postman(under the save button)
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("from", "example#email.com");
urlencoded.append("test", "test");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("http:localhost:6060/, requestOptions)
.then(response => {
if (response.ok){
response.json().then(json => {
console.log(json)
})
}
})
.catch(error => console.log('error: ', error))
I have a question. I have a requirement which needs to get something from local storage and set it as short name in manifest.json. I am building a progressive web app and it is vital to have manifest.json to configure its settings. Do you have any idea how to do it? I would gladly appreciate any kind of help. Thank you!
You can make a endpoint in your system with the data that you want to insert into the manifest.json, in Express would be something like this (I didn't worried about security)
server.js
const express = require('express')
const app = express()
const fs = require('fs')
app.use(express.json())
app.get('/', (req, res) => res.sendfile('./index.html'))
app.post('/', (req, res) => {
fs.writeFileSync('./file.json', JSON.stringify({
description: req.body.description
}, null, 2), (err) => {
if (err) throw err
res.send(`The new description is: ${req.body.description}`)
})
})
app.listen(3000, () => console.log('server is listening'))
client.js
(async() => {
const result = await fetch('http://localhost:3000', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
description: 'only for testing purposes'
})
})
console.log(await result.json())
})()