I need to receive a JSON from my front in React. But the JSON comes to me in a strange way (an object with the data in string), I don't know how to return it to type object again.
I send this.
const data = {
email: 'emailc#email.com',
password: 'test'
}
const options = {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const onsubmit = (e) => {
//evitamos que se haga la peticion en automatico
e.preventDefault();
fetch('http://localhost:3001/user/signin',options)
.then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
console.log('send on submit');
}
and I get this on the express server:
[Object: null prototype] {
'{"email":"emailc#email.com","password":"test"}': ''
}
My server is configured in this way:
const express = require('express');
const app = express();
const morgan = require('morgan');
const cors = require('cors');
const {mongoose} = require('./src/database/connection')
const Parser = require("body-parser").urlencoded({ extended: false });
//config
app.set('port', process.env.PORT || 3001);
//middlewares
app.use(morgan('dev'));
app.use(Parser);
app.use(cors()); //accepts connection from all directions
//Routes
app.use(require('./src/test'));
app.use(require('./src/routes/users'));
//Server
app.listen(app.get('port'), (req, res) => {
console.log(`Server on port ${app.get('port')}`);
})
I think I have misconfigured the body-parser, please help, it is my first API.
'Content-Type': 'application/x-www-form-urlencoded'
If you tell the server you are sending Form Encoded data then it is going to try to parse what you send as Form Encoded data.
Don't lie.
If you are sending JSON, say so:
'Content-Type': 'application/json'
const Parser = require("body-parser").urlencoded({ extended: false });
You also need a body parser that supports JSON.
const Parser = require("body-parser").json();
But Express has a built-in body parser and variable names starting with capital letters are traditionally reserved for constructor functions / classes.
const parser = express.json();
Aside:
mode: 'no-cors'
If you are making a cross-origin request then that will break it.
If you are making a same-origin request then that will do nothing.
Remove it.
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});
})
My request.body is returning an empty object in express 4.17.1.
It works fine on postman, but when I try consuming it at the frontend using javascript I get an empty object, even when I console.log it
Below is my code:
/////Express backend
const express = require('express');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
////React frontend
const myData = {
_id: "616a4663c3086a539a8c3dcc",
type: "describe_yourself",
name: "white"
}
React.useEffect( () => {
fetch('http://localhost:9000/test', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(myData)
}).then(response => response.json())
.then(data => console.log(data))
}, [])
I am not using body-parser because it is deprecated.
I will really appreciate anyone that can help me. thanks in advance
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'
I have a node.js app connected to a dialogflow bot I created, in which there's only one file: app.js.
I have index.html, index.js UI for the bot, which when I open unconnected to app.js, runs perfectly. I get json response from app.js
However, when I tried to include the UI (index.html and index.js) in app.js, the post method is returning index.html instead of the json it returned before, resulting in error: "SyntaxError: Unexpected token < in JSON at position 0" (because index.html is returned instead of json)
Here's my app.js
const dialogflow = require('#google-cloud/dialogflow');
const uuid = require('uuid');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 9000;
const sessionId = uuid.v4();
app.use(bodyParser.urlencoded({
extended: false
}));
// ------------------The following code is the one I use for including the UI----------------------------------
const path = require('path');
app.use(express.static('botui'));
app.use('/', function(req,res){
res.sendFile(path.join(__dirname+'/botui/index.html'));
});
// ------------------------------Code for including the UI ended-----------------------------------------------
// ------------------When I did not use the above code and just opened file://index.html it worked great-------
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.post('/send-msg',(req,res)=>{
runSample(req.body.MSG).then(data=>{
res.send({
statusCode: 200,
body: {},
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
Reply:data})
})
})
/**
* Send a query to the dialogflow agent, and return the query result.
* #param {string} projectId The project to be used
*/
async function runSample(msg, projectId = 'bot_ID') {
// Create a new session
const sessionClient = new dialogflow.SessionsClient({
keyFilename:"BOT-KEY.json"
});
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: msg,
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
return result.fulfillmentText;
}
app.listen(port,()=>{
console.log("Running on port: " + port)
})
And here's the code from index.js which sends the POST request:
fetch(url, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
method: 'POST',
body:data
})
.then(res => res.json())
.then(response => {
console.log(response);
serverMessage(response.Reply);
})
.catch(error => console.error('Error h:', error));
It seems you should replace app.use('/', function(req,res){ to app.get('/', function(req,res){
take a look at Difference between app.use and app.get in express.js
I'm trying to make an HTTP Post request to my Node server from an html form. I use the Body Parser and everything but when I try to fetch the request, and log the req.body in my server, it's an EMPTY object. Do you know how I can fix this?
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const email = document.querySelector('#email').value;
const password = document.querySelector('#password').value;
const formData = { email, password };
const options = {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(formData),
mode: 'no-cors'
};
fetch('http://localhost:3000/users/login', options)
.then(res => {
console.log(res);
res.json();
})
.then(data => {
console.log(data);
});
You said mode: 'no-cors' so everything that requires CORS permission is ignored (including setting the Content-Type header to application/json).
Remove mode: 'no-cors' (and use the cors middleware on the server).