Question about connecting React and NodeJS express - javascript

I tried to connect between React(Front End) and NodeJs(BackEnd) and NodeJS -> React(GET) worked well but React -> NodeJS(POST) always erred "POST http://localhost:3001/board/giveresult 500 (Internal Server Error)" and "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" I did all the way to solve that problem but I was stuck at that for a week. what is the problem?
// Method in React
setData() {
let data = {
id:this.state.contents.id, //contents is array in the state
write:this.state.contents.writer,
title:this.state.contents.title,
description:this.state.contents.description
}
fetch('http://localhost:3001/board/giveresult'
,{
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(data)
})
.then (res => res.json())
.then (data => console.log(data));
}
//NodeJS Express
const express = require('express');
const app = express();
const receive = require('./routes/receive')
const giveResult = require('./routes/giveResult')
const port = process.env.PORT || 3001;
const cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(bodyParser.json())
app.use('/board/giveresult', giveResult);
app.use('/board/receive', receive);
app.listen(port, function(){
console.log(`connected ${port} port!`);
});
//giveResult
var express = require('express');
const router = express.Router();
var mysql = require('mysql');
const dbconfig = require('../mysql.js');
const { Router } = require('express');
const connection = mysql.createConnection(dbconfig);
var bodyParser = require('body-parser');
router.post('/', function(req, res) {
if(err) throw err;
var post = req.body.id;
console.log(post)
res.send('suceess!!!!');
});
module.exports = router;

Try adding accept in your request header be like .
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}

Related

Unexpected field ERROR in multer file upload

I'm setting up a server to run my project and using multer on the backend. However, whenever I try to send an image from my frontend to the backend, i get message: "Unexpected field", name: "MulterError", frames.
dependencies that i'm using in my server.js:
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
var singleUpload = upload.single('featuredImage');
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const cors = require('cors');
var axios = require("axios");
code in server.js:
app.use(bodyParser.json())
app.use(cookieParser())
app.post('/uploads', singleUpload, function (req, res, next) {
axios.post('http://api.com/api/public/nuxt',
upload,
{
headers:
{
'Content-Type': 'multipart/form-data',
}
})
.then(function(result) {
console.log('SUCCESS!!!!!!!!!!!');
console.log(result.data);
}) .catch(function(){
console.log('FAILURE!!!!1!!!!');
});
return res.json({"status":"success"})
})
module.exports = app

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Why does the bodyParser not working?

This is my index.js file and i think i have placed the routes after installing bodyParser but still getting the syntax error.
const express = require('express'); //Framework to build server side application
const morgan = require('morgan'); //Logging the nodejs requests
const bodyParser = require('body-parser'); //To get the JSON data
const urls = require('./db/urls');
const app = express();
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(express.static('./public')); //If a request comes with '/' check if file is in there if it is then serve it up.
// app.get('/', (req, res) => {
// res.send('Hello, World !!');
// });
app.post('/api/shorty', async (req, res) => {
console.log(req.body);
try {
const url = await urls.create(req.body); //Passing the body data which is JSON to create function
res.json(url);
} catch (error) {
res.status(500);
res.json(error)
}
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
This is the urls.js file,I am not getting where have i messed up to make Syntax.JSON error in this file.
const db = require('./connection');
const Joi = require('joi');//Schema validation
const urls = db.get('urls');
const schema = Joi.object().keys({
name : Joi.string().token().min(1).max(100).required(),
url : Joi.string().uri({
scheme: [
/https?/ //get http 's' is optional
]
}).required()
}).with('name','url');
//almostShorty = {
// name = ,
// url =
// }
function create(almostShorty){
const result = Joi.validate(almostShorty, schema);
if(result.error === null){
return urls.insert(almostShorty);//Inserting the object in the Data Base.
}else{
return Promise.reject(result.error);
}
};
module.exports = {create};//Exporting the create function.

Error: Request failed with status code 404 (Node.js + Vue.js)?

I am little bit confused and need some help.
I write an HTTP server using Node.js, and make an HTTP request from Vue.js to the HTTP server. Somehow it always return error like this:
Error: Request failed with status code 404
at FtD3.t.exports (createError.js:16)
at t.exports (settle.js:18)
at XMLHttpRequest.f.(:3010/anonymous function) (http://localhost:3010/static/js/vendor.1dc24385e2ad03071ff8.js:1312:88758)
It seems like url address don't correct cause error is 404 in browser. I check url address several times but did't notice something wrong. What I miss?
P.S. The main task to load file from remote sftp server from website. I use to that task ssh2-sftp-client library as backend side.
When user click the button, application run getFile function where we send post request to HTTP server.
Code inside Vue.js component:
getFile (fileName) {
axios.post('http://localhost:3010/csv', {file_name: fileName}, {headers: {'Authorization': this.token}}).then(response => {
console.log(response)
this.showAlert('You download file successfully.', 'is-success', 'is-top')
}).catch((error) => {
console.log(error)
this.showAlert(error, 'is-danger', 'is-bottom')
})
}
app.js:
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const path = require('path');
const bodyParser = require('body-parser');
const csvRouter = require('./server/routes/csv')
const app = express();
app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/csv', csvRouter);
module.exports = app;
routers/csv.js:
const express = require('express')
const router = express.Router()
const csvControllers = require('../controllers/csv')
router.get('/', csvControllers.getFile)
module.exports = router
controllers/csv.js:
const request = require('request')
const queryString = require('query-string')
let Client = require('ssh2-sftp-client')
let sftp = new Client()
const config = require('../config')
exports.getFile = (req, res) => {
console.log(req) // In console I don't notice nothing.
let data = {
file_name: req.query.file_name
}
let options = {
method: 'port',
json: true,
header: {'Authorization': req.header.token},
url: `http://localhost:3010/csv?` + queryString.stringify(data)
}
request(options, (error, response) => {
console.log('Message') // In console I don't notice nothing.
if (response) {
sftp.connect(config.sftpServer).then(() => {
return sftp.get('/reports/' + data.file_name)
}).then((chunk) => {
console.log(chunk)
}).catch((err) => {
console.log(err)
})
} else {
response.status(500).send(error)
}
})
}
It seems that app.listen(port) is missing in your app.js file:
app.listen(3000)
https://expressjs.com/en/starter/hello-world.html
In controllers/csv.js you never send a response. You should have a res.send or res.render or res.json somewhere.

Error setting cookie and getting a json response with router.post in express, node.js

I'm trying to set a cookie with a post method in order to do some db query and put it back in the cookie value, as well as returning a json with the user data.
It works, the cookie is set and I get the json on http://localhost:8080
but I get a message from the compiler:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How can I fix it so it won’t make this error?
my file structure is:
root/ app.js
root/controllers/ cookie.controller.js
root/routes/ cookie.route.js
app.js
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || process.argv[2] || 8080;
app.use(cookieParser());
app.use(require('./routes/cookies'));
app.use(cors());
app.listen(port, () => console.log('cookie-parser demo is up on port: ' + port));
cookie.route.js
const express = require('express');
const cookieController = require('../controllers/cookies');
const router = express.Router();
router.use(require('cookie-parser')());
router.post('/', router.use(cookieController.getCookie));
module.exports = router;
cookie.controller.js
exports.getCookie = (req, res, next) => {
let auth = req.cookies.auth;
//...db queries, get userData
let userData = {
id: '123',
token: 'sfsdfs34',
email: 'user#gmail.com'
};
// if cookie doesn't exist, create it
if (!auth) {
res.status(200)
.cookie('auth', userData.id)
.json({ message: 'it works!', user: userData });
req.cookies.auth = userData.id;
}
next();
};
You're modifying the request cookie headers after sending the response at the end of your getCookie controller. You should remove req.cookies.auth = userData.id, and use res.cookie() instead before sending the response.
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
app.use(cookieParser())
app.get('/', (req, res) => {
if (!req.cookies.auth) {
res.cookie('auth', { id: '123' })
}
res.json({ message: 'It worked!' })
})
app.listen(8080, () => console.log('http://localhost:8080))
Problem was solved after deleting the cors from app.js

req.cookies returns undefined but cookies are set

I am using cookie-parser in my express app. When the root page is requested I set a random number on the cookie using res.cookie(name, value) and it sets it fine (I checked on my browser console). But when I try to log req.cookie it always returns undefined.
Here's my code:
routes.js
var express = require('express')
var router = express.Router()
var movieTrailer = require('movie-trailer');
var Promise = require('bluebird');
var logs = require('log-switch');
var fs = require('fs');
//var cookieParser = require('cookie-parser');
//Setup x-ray for scraping
var Xray = require('x-ray');
var x = Xray();
var debug = false;
router.get('/', (req, res) => {
console.log('Page requested!');
console.log('Cookies: ', req.headers.cookies); // For some reason this returns undefined
var scrapeMovies = function(){
return new Promise((resolve, reject) =>{
fs.readFile('moviesRT.json', (err,data) =>{
var movies = JSON.parse(data);
resolve(movies);
});
});
};
scrapeMovies().then(
movies => {
var randomInt = Math.floor(Math.random() * movies.length);
res.cookie('randomInt', randomInt);
var randomMovie = movies[randomInt];
movieTrailer(randomMovie.title, (err, url) =>{
console.log('Requesting trailer: ', randomMovie.title);
if(err) throw err;
var embedUrl = url.replace('watch?v=','embed/');
console.log('Video ID: ', url.slice(32,url.length));
randomMovie.trailerURL = embedUrl; //Add the embed URL to the randomMovie object before rendering it
res.render('main',randomMovie,
(err, html) =>
{
if(err) throw err;
console.log('Rendering...');
res.send(html);
console.log("Done!");
});
});
});
});
module.exports = router;
app.js
const express = require('express');
//Define app and settings
const app = express();
const exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
const port = 3000;
var routes = require('./routes');
var debug = true;
app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
//app.use(cookieParser());
//View engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.listen(port, function () {
console.log(`Server Starts on ${port}`);
if(!debug) logs.disable(); //Disable logging if debug variable is false
});
You either want to check req.headers.cookie which will be set by express.
Or if you want to use the the parsed result of the cookie-parse middleware that is stored inreq.cookies then your problem is the order in which you register your routes and the middleware.
app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
The parsing of the cookie is done after the routes in routes have ben executed.
You need to move the cookieParser() before the route where you want to use it.
app.use(cookieParser());
app.use('/', routes);
app.use(express.static('public'));
This solved my problem:
Basically when you are sending a request to the server from client-side, make sure you add withCredentials: true. For example
{
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
}),
'withCredentials':true
};
This happened to me, when I sent a PUT request from the client-side (Angular) without passing the body object.
I was doing this (second argument missing):
requestBranchEditPermission() {
return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, this.options).toPromise();
}
instead of this:
requestBranchEditPermission() {
return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, {}, this.options).toPromise();
}
You will need to read the cookies as req.cookies['cookie-name'] and set the cookies as resInit.cookie('cookie-name', 'cookie-value')
This worked for me
in the frontend add credentials : 'include' as an option to your fetch API
A more elaborated code below for a get request
fetch('url', {credentials: 'include'})
.then(res => res.json())
.then(data => //do something with the data)
.catch(err => console.log(err.message));

Categories

Resources