I have a task to implement a pseudo cart page and when I click on checkout i want to send a request to a json file "ordersTest.json" with a following structure:
{ "orders": [] }. So when a post request is sent i have to put the data in that orders array in the json. I am completely new to Nodejs and express. This is my first project on it and i came up with a very simple server.
const express = require('express')
const path = require('path')
const fs = require('fs')
const url = require('url')
const bodyParser = require('body-parser')
const app = express()
const ordersJson = require('./public/ordersTest.json');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/api/orders', (req, res) => {
let body = req.body;
console.log(body);
fs.appendFile('./public/ordersTest.json', JSON.stringify(body), err => {
if (err) console.log(err);
})
})
But this thing only appends it to the end of the file. I need to put it inside this orders array
This is my ajax passing an example object in the body of the post:
$(".btn-checkout").on('click', function() {
let date = new Date();
$.ajax({
method : "POST",
url: "/api/orders",
data : {a: "abc"},//{ order: "order",date: date.toDateString(), order: JSON.stringify(cart)},
success : function(success){
console.log(success,'success');
},
error : function(err) {
console.log(err);
}
});
clearCart();
displayClearedCart();
});
You need to parse the JSON file and then treat it like an object. Once you are done with it, convert it to JSON again and overwrite your file. like this
app.post('/api/orders', (req, res) => {
let body = req.body;
var ordersTest = require('./public/ordersTest.json');
ordersTest.orders.push(body);
fs.writeFile('./public/ordersTest.json', JSON.stringify(ordersTest), function(err) {
if (err) res.sendStatus(500)
res.sendStatus(200);
});
})
Not tested, please fix typo error if any.
Related
I have a frontend JS script that takes text input from an HTML text box and sends it to an expressjs server. The body of the POST request, though, is always undefined, or depending on how I tweak things, returning as "{ }" if I view it via console.log( ). As I'm new to this, I can't seem to see what's going wrong.
Front end js:
async function submitCity(){
let x = document.getElementById("wg_input").value;
console.log("Successfully captured city name:", x);
let toWeather = JSON.stringify(x);
console.log("Input data successfully converted to JSON string:", toWeather);
const options = {
method: 'POST',
mode: 'cors',
headers: {'Content-Type': 'text/plain'},
body: toWeather
}
fetch('http://localhost:3000', options)
.then(res => console.log(res))
.catch(error => console.log(error))
}
Backend:
// Dependencies
const express = require('express');
const bp = require("body-parser");
const request = require("request");
const jimp = require('jimp');
const cors = require('cors');
const wgServer = express();
const port = 3000;
// Dotenv package
require("dotenv").config();
// OpenWeatherMap API_KEY
const apiKey = `${process.env.API_KEY}`;
// Basic server initialization
wgServer.use(cors())
wgServer.use(bp.json())
wgServer.use(bp.urlencoded({ extended: true }))
wgServer.listen(port, function() {
console.log(`Example app listening on port ${port}!`)
});
wgServer.post('/', async function (req, res) {
res.set('Content-Type', 'text/plain');
console.log(req.body)
res.send('Hello World');
//const data = await req.body;
// let jsonData = JSON.stringify(req.body);
// res.status(201);
//res.json();
});
The returned data is supposed to be a string of about 15 characters, give or take a few (a city and state). I thank you in advance.
I was setting a weather app website that is connected to another site using a server, and asynchronous javascript was used, but after trying to run the code, an error reading "uncaught syntax error: unexpected end of input" in the last line in the app file...I don't understand what it means and therefore I don't know how to solve it
here's my app file code
/* Global Variables */
const apiKey = "726f360f99f8ed5ce834f19b2f632fd3"
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = +d.getMonth()+1+'.'+ d.getDate()+'.'+ d.getFullYear();
const gen = document.querySelector("#generate");
gen.addEventListener("click", async() =>{
const Zcode = document.querySelector("#zip").value;
const feel = document.querySelector("#feelings").value;
try {
getTemp()
.then(temp =>{
const object = {
date: newDate,
temp: temp,
}
return DealingWithServer()
})
.then(data =>{
UpdateSite(data)
})
}catch(error){
console.log(error);
}
});
async function getTemp (){
const res = await fetch (`https://api.openweathermap.org/data/2.5/weather=?zip=${zipCode}&appid=${apiKey}&units=metric`);
const data= await res.json;
const temp = data.main.temp
return temp
}
async function DealingWithServer (){
await fetch('/recieve', {
method: "POST",
credentials: "same-origin",
headers: {"Content-Type": "application/json"},
body:JSON.stringfy({
date: newDate,
temp: temp,
feel: feel
})
});
const Sres = await fetch('/get', {credentials: "same-origin"});
const Sdata = await Sres.json()
return (Sdata);
}
function UpdateSite (data)
and my server file code
// Setup empty JS object to act as endpoint for all routes
projectData = {};
const port = 3000;
// Require Express to run server and routes
const express= require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
// Start up an instance of app
const app=express()
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static('website'));
app.get("/get",(req, res) => {
res.send(projectData)
})
app.post("/recieve", (req, res) => {
projectData =req.body
res.status(200)
})
// Setup Server
app.listen(3000,() =>{
console.log("Server running");
})
It looks to me like you've not finished your UpdateSite function at the bottom. It should read something like this:
function UpdateSite (data) {
// Do things to update the site
}
Since there is no function definition, the input (JavaScript code in this case) has ended unexpectedly - i.e. the parser was not expecting the input to end with function UpdateSite (data)
I'm making a post request using axios and passing in a body like so:
export const uploadFeatured = (userId, uploadInfo) => async dispatch => {
////console.log("uploading", uploadInfo.mediaName, uploadInfo.video, uploadInfo.description);
const res = await axios.post(domain + '/api/uploadFeatured',
{mediaName: uploadInfo.mediaName,
video: uploadInfo.video,
description: uploadInfo.description});
console.log("response to upload", res)
}
However, at the server, I'm getting an undefined when accessing req.body.
app.post("/api/uploadFeatured", async (req, res) => {
try {
//////// req.body returning undefined.
console.log("upload featured is ", req.body)
const data = {name:"Name"}
const newFeatured = new Featured(data).save();
const client = algoliasearch('YD', '055b10');
const index = client.initIndex('Humboi');
index.saveObjects([data], {
autoGenerateObjectIDIfNotExist: true
}).then(({ objectIDs }) => {
console.log(objectIDs);
});
console.log("new featured is ", newFeatured);
} catch (e) {
console.log("error ", e)
}
});
What am I doing that's causing the body to be undefined in the node.js server rather than to be the map that's passed in axios?
Please install body-parser add following code in your js file after const path:
npm install body-parser
const bodyParser = require('body-parser')
app.use(bodyParser);
The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.
I am trying to implement a typeahead functionality as below.
html page
...
...
<input id="product" name="product" type="text" class="form-control" placeholder="Enter Product Name" autocomplete="off">
...
...
<script>
$(document).ready(function () {
fetchTypeAheadResult();
});
function fetchTypeAheadResult() {
$('#product').typeahead({
source: function (request, response) {
var formData = {
'product' : $('#product').val()
}
// var formData = $('form').serialize();
$.ajax({
url: "/search",
dataType: "json",
type: "POST",
data: formData,
contentType: "application/json; charset=utf-8",
success: function (result) {
var items = [];
response($.map(result, function (item) {
items.push(item.name);
}))
response(items);
// SET THE WIDTH AND HEIGHT OF UI AS "auto" ALONG WITH FONT.
// YOU CAN CUSTOMIZE ITS PROPERTIES.
$(".dropdown-menu").css("width", "100%");
$(".dropdown-menu").css("height", "auto");
$(".dropdown-menu").css("font", "12px Verdana");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
hint: true, // SHOW HINT (DEFAULT IS "true").
highlight: true, // HIGHLIGHT (SET <strong> or <b> BOLD). DEFAULT IS "true".
minLength: 1 // MINIMUM 1 CHARACTER TO START WITH.
});
}
</script>
...
...
And my back end node js code is as following
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
// configure the app to use bodyParser() to extract body from request.
app.use(bodyParser.urlencoded({ extended: true }));
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));
app.post('/search', (req, res) => {
let searchText = req.body;
console.log('Search string >> ' + req);
console.log('Search string >> ' + JSON.stringify(req.body));
console.log('Search string >> ' + req.body.product);
// Not correct, but still trying if it works
// var result = triestrct.get(req.body.product);
res.send({test:'text'}); // TODO - to be updated with correct json
});
Now whenever I am trying to type on the "product" text field, it is invoking the back end /search api. However, I am unable to capture the value of product field.
Any help will be appreciated ? Note, I need typeahed functionality with ajax call to send input text value to back end.
Output of the three consol logs as following...
Search string >> [object Object]
Search string >> {}
Search string >> undefined
express doesn't parse the input provided to API by it self. Thus we need some additional tool like body-parser to fetch input from request and format it into JSON. This can be done without body-parser too.
Do go through this documentation it covers a lot.
Using body-parser, you need to setup body-parser with express:
```
const bodyParser = require('body-parser'),
// For Cross-Origin Resource Sharing
CORS = require('cors'),
express = require('express');
const app = express();
// Cross-Origin Resource Sharing
app.use(CORS());
// configure the app to use bodyParser() to extract body from request.
// parse urlencoded types to JSON
app.use(bodyParser.urlencoded({
extended: true
}));
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));
// This will get you input at `req.body`
app.post('/search',(req,res)=>{
console.log(JSON.stringify(req.body));
});
```
Without using body-parser:
```
app.post('/', (req, res, next) => {
let body = [];
req.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
// Without parsing data it's present in chunks.
body.push(chunk);
}).on('end', () => {
// Finally converting data into readable form
body = Buffer.concat(body).toString();
console.log(body);
// Setting input back into request, just same what body-parser do.
req.body = body;
next();
});
}, (req, res) => {
console.log(req.body);
});
```
req.body.product not req.query.product
IN POST verb use body-parser midlleware
const bodyParser = requier('body-parser');
const express = require('express');
const app = new express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post('/search',(req,res)=>{
console.log(JSON.stringify(req.body));
});
I did not use typeahead before but this example is clear.
I have a RESTful API that I am using postman to make a call to my route /websites. Whenever I make the call, postman says "Cannot POST /websites". I am trying to implement a job queue and I'm using Express, Kue(Redis) and MongoDB.
Here is my routes file:
'use strict';
module.exports = function(app) {
// Create a new website
const websites = require('./controllers/website.controller.js');
app.post('/websites', function(req, res) {
const content = req.body;
websites.create(content, (err) => {
if (err) {
return res.json({
error: err,
success: false,
message: 'Could not create content',
});
} else {
return res.json({
error: null,
success: true,
message: 'Created a website!', content
});
}
})
});
}
Here is the server file:
const express = require('express');
const bodyParser = require('body-parser');
const kue = require('kue');
const websites = require('./app/routes/website.routes.js')
kue.app.listen(3000);
var app = express();
const redis = require('redis');
const client = redis.createClient();
client.on('connect', () =>{
console.log('Redis connection established');
})
app.use('/websites', websites);
I've never used Express and I have no idea what is going on here. Any amount of help would be great!!
Thank you!
The problem is how you are using the app.use and the app.post. You have.
app.use('/websites', websites);
And inside websites you have:
app.post('/websites', function....
So to reach that code you need to make a post to localhost:3000/websites/websites. What you need to do is simply remove the /websites from your routes.
//to reach here post to localhost:3000/websites
app.post('/' , function(req, res) {
});