No response from Express + postman - express

I cannot seem to POST data via Postman & Express.
My POST verb code is as follows
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
var fdbRouter = express.Router();
fdbRouter.route('/films')
//post verb
.post(function (req, res) {
var item = new Film(req.body);
console.log(item);
//item.save();
res.status(201).send(item);
})
And my Postman setup is as follows
I have befriended google and came up with this
1. Node.js/Express form post req.body not working
2. req.body empty on posts
3. Express + Postman, req.body is empty
4. `express` app - not able to test the `post` request using `postman`
PS The watched item in postman is default in the mongoose schema i have so it's created regardless whether express works or not.

Whenever I have worked with a post request in express it's been formatted as below (assuming you're using mongoDB):
var express = require('express');
var fdbRouter = express.Router();
var model = require("<FILE TO IMPORT MODEL>") //This file will differ, but you need to import the model you created for films in your DB
var FilmModel = model.Film //also depends on how you exported your model in your dbFiles. Either way you need this model as the blue print for your post request
//I'm also assuming here that you're calling /films correctly and have it sourced as such in your app.js so you don't need /api/films as you have listed in your postman setup image
fdbRouter.post('/films', function(req,res){
var newfilm = new FilmModel()
newFilm.title = req.body.Title
newFilm.year = req.body.Year
newFilm.genre = req.body.Genre
newFilm.save(function(err, savedObject){
if(err){
console.log(err)
res.status(500).send()
}else{
res.send(savedObject)
}
})
})
Please note: this code example assumes a test db with a schema and model has been setup and is available for import to your routes file.
Let me know if this puts you on the right track!

Related

Azure Search API throws CORS error even when CORS is enabled

I have an Azure search index called users that has CORS configured to * (for now) to allow all origins. When I make a GET request to it programmatically using fetch or axios, I get a CORS error:
Access to XMLHttpRequest at 'https://MY_SEARCH_SERVICE.search.windows.net/indexes/users/docs?api-version=2021-04-30-Preview&%24top=5&search=matt*&%24searchFields=name&%24select=id%2Cname%2Cemail&api-key=MY_API_KEY' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
However, if I put the same GET URL into a browser, it returns the list of expected results with no errors.
Here's my code (to run, create a Svelte app and put this in App.svelte or use the Svelte REPL. You must also have an Azure Search service set up, and you'll need to replace the placeholder variables MY_SEARCH_SERVICE and MY_API_KEY with your own, along with an index on which you want to try this):
<script lang="ts">
import { onMount } from "svelte";
const service = "https://MY_SEARCH_SERVICE.search.windows.net";
const index = "users";
const endpoint = `${service}/indexes/${index}/docs`;
const params = new URLSearchParams({
"api-version": "2021-04-30-Preview",
"api-key": "MY_API_KEY",
"$top": "5",
"$searchFields": "name,email",
"$select": "id,name,email"
});
const headers = new Headers({
"accept": "application/json"
});
onMount(async () => {
console.log(`${endpoint}?${params}`);
const response = await fetch(`${endpoint}?${params}`, {
headers: headers
});
console.log(await response.json());
});
</script>

How to retrieve form-data values in Express js?

I created a form data in Postman and send a http post request. but when I send the request, it shows there is no form data in the destination!
here is my codes in backend :
app.js file:
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var routesImagesApi = require('./api/routes/imagesrouters');
app.use('/api/images', routesImagesApi);
api/routes/imagesrouters.js file:
var router = express.Router();
var ctrlAuth = require('../controllers/images');
router.post('/imageUpload', ctrlAuth.imageUpload);
controllers/images.js file:
module.exports.imageUpload = function (req, res) {
res.status(200);
res.json({"Returned data":req.body});
}
I created a request in postman with two key-value form-data body.
here is my request:
POST > http://localhost:3000/api/images/imageUpload
and form-data body key-values are these :
key:name , value:Sarah
key:family , value:Thomas
Below image is Postman screenshot :
I expected postman show me the form-data key values but as you can see it shows nothing!
{
"Returned data": {}
}
Do you have any idea?
Please use the multer package or you could write a custom handler for making express handle multi part form data i.e "files/imgs..etc "
multer package
and
writing your own custom handler
p.s this could be a duplicate issue

How does redirecting from a post method to get method work?

The server doesn't recognize any get request except for the post method after executing some queries in the mongodb.
The express middleware takes the post method and after interacting with the database and using the res.redirect() to get to other get methods, the server doesn't recognize the request at all. I tried using res.all(). This showed that the request was seen but no action was taken.
var express = require('express');
var router = express.Router();
var Product = require('../models/product');
router.get('/', function(req, res, next) {`//homepage
res.render("index");
}
router.post('/add',function(req,res next){
//Product model
var prod = new Product({
//data here
});
prod.save(function(err,res2){
if(err){
console.log(err);
return res.redirect('/error');
}
else{
mongoose.disconnect();
console.log("Complete1");
return res.redirect('/');
console.log ("Complete2);
}
});
}
After I get to the post method it should redirect to the homepage
The problem may not be with the backend, but with the frontend. If you are using AJAX to send your POST request, it is specifically designed to not change your url.
Use window.location.href after AJAX's request has completed (in the .done()) to update the URL with the desired path, or use JQuery: $('body').replaceWith(data) when you receive the HTML back from the reques

Recreate a post request in postman

I have the following javascript code, to produce a post request.
var postUrl = "http://localhost:3100/radiance";
xhttp.open("POST", postUrl, true);
xhttp.setRequestHeader('Content-type', 'application/json');
let radFile = {"radfile":"long string"}
let solarJson = {"key1":"value1","key2":"value2"}
let latitude = 45
let longitude = 24
msgJson=JSON.stringify({'radFile':radFile,'speedSolar':solarJson,'latitude':latitude,'longitude':longitude})
xhttp.send(msgJson);
The post request works absolutely fine with my express app code below.
var express = require('express');
// require our dependencies
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var port = process.env.PORT || 3100;
var corsOptions = {
credentials: false
};
// use body parser
app.use(bodyParser.urlencoded({extended: true, limit: 1024 * 1024 * 10000, parameterLimit: 1000000*1000}));
app.use(bodyParser.json({type: 'application/json', extended: false, limit: 1024 * 1024 * 10000, parameterLimit: 1000000*1000}));
// route our app
var router = require('./app/routes');
app.use('/', router);
var server
// start the server
server = app.listen(port, function() {
console.log('app started ' +port );
});
However I am struggling to replicate the post request above in post man for testing (purposes).
I believe that the following post request should do the trick but when my app recieves this post request the body of the request is always empty. Why? It seems that the body parser isnt doing it's job.
What I am doing wrong in my post request in postman, how can I replicate my javascript post request exactly?
You are doing two different types of request here. Your website code is sending a JSON string with the contents of the 'files' embedded into it:
let radFile = {"radfile":"long string"}
let solarJson = {"key1":"value1","key2":"value2"}
let latitude = 45
let longitude = 24
msgJson=JSON.stringify({'radFile':radFile,'speedSolar':solarJson,'latitude':latitude,'longitude':longitude})
gives you a body of
{'radFile': {"radfile": "long string"}, 'speedSolar': {"key1":"value1", "key2":"value2"}, 'latitude': 45, 'longitude': 24}
However, when you are using Postman as you are, you are submitting 2 different pieces, a file (or 2) and the form values - you can use the postman echo site to see what you are actually submitting, in case you have questions in the future:
If you really want to replicate your original version, you can do this - a raw body of type json, and fill in the details:

Where do you place NPM's request code?

I want to use the request module in my express app, but I am not sure where the actual requests code goes.
Usage:
When a user loads a page, make a GET request and populate the page with data.
When a users clicks on a item from a table, make a GET request.
When a user fills out a form, POST.
I tried searching for answers but it seems to be implied that the developer knows where to place the code.
Example of a code snippet using request that I am unsure where to place in the express app:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
I am guessing that I should not place the code in the server.js file especially if I am going to be making many different calls, but that's what it looks like others are doing on StackOverflow.
Does the request belong in a model?
If you are doing this in response to a user interaction, like clicking on something you can just do it from the route handler. Below, I just return the results to the client, or I pass an error to the next handler in the chain.
var request = require('request');
var express = require('express');
var app = express();
app.get('/click', function(req, res, next){
request('http://www.google.com', function (error, response, body) {
if (error || response.statusCode != 200)
return next(err);
response.send(body) // return the html to the client
})
});
app.listen(3000);
In bigger apps you might move routes into separate modules.