avoid caching in rest api using node.js - json

I searched a lot about the subject and why/how to avoid restfull api caching, butI didn't get a helpful answer.
I built expressjs api to generate random json data using faker module everything went fine for the first request but any refresh on the browser or any additional requests display the same data.
I want with every request generate a random data but I think after the first request the nodejs module is cached.
I'm using
nodejs: the latest version,
expressjs: v4.0,
faker: the latest
my code as below:
in the router file: router.js
var router = express.Router();
router.get('/name', controller.name);
.
.
in the controller file: json.controller.js
//Get name
var name = require('name.model.js');
exports.name = function(req, res){
var randomName = name;
return res.json(200, randomName);
};
in the model file: name.model.js
var faker = require('faker');
var nameModel = {};
nameModel.name = faker.name.findName();
module.exports = nameModel;
Can any one help how to avoid rest api caching? and how to fix it in my case?
Thanx for any help,

The problem was that I didn't understand moduke.exports and exports in node.js
After reading Understanding module.exports and exports in Node.js
I changed the module to be:
var exports = module.exports = {};
exports.getName = function(){
return faker.name.findName();
}
Voila! that fixed the issue I was facing, and I started getting new data everytime I post a request to the server.
I hope this will help any one needs to understand module.exports and exports

Related

Error.invalid json response Unexpected token T in JSON at position 0 sanity nextjs typscript [duplicate]

This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed 4 months ago.
hey i guys i have a question i did the build with react and typscript and sanity cms but the problems is when im trying to deploy the build to varcel it keeps rejecting it sayning that FetchError: invalid json response body at https://portfolio2-1-wn3v.vercel.app/api/getExperience reason: Unexpected token T in JSON at position 0 while it works on my local machine it find all the data and everything ... i read that it might be a problem somewhere down the line with getStaticProps or when fetching json and yes i did change the enviroment varibals from base_url in http 3000 to the varcel ones but other than that i have no idea what else i should do .... if anyone has any expirince with this kind of errors ? here is my code for the
`import {Experience} from '../typings'
export const fetchExperiences = async () =>{
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getExperience`)
const data = await res.json()
const projects:Experience[] = data.experience
return experience
}`
the getExercise.ts file has all the api request
import type{NextApiRequest,NextApiResponse} from 'next'
import {groq} from 'next-sanity';
import {sanityClient} from '../../sanity';
import {Experience} from '../../typings'
const query = groq`
*[_type == "experience"]{
...,
technologies[]->
}
`;
type Data ={
experience:Experience[]
}
export default async function handler(
req:NextApiRequest,
res:NextApiResponse<Data>,
){
const experience:Experience[]= await sanityClient.fetch(query)
res.status(200).json(JSON.parse(JSON.stringify({experience})))
}
and this is the index.ts file part
export const getStaticProps: GetStaticProps<Props> = async() => {
const experience : Experience[] = await fetchExperiences();
const skills : Skill[] = await fetchSkills();
const projects : Project[] = await fetchProjects();
const socials : Social[] = await fetchSocials();
return{
props:{
experience,
skills,
projects,
socials,
},
revalidate:10
}
}
The error link you see (https://portfolio2-1-wn3v.vercel.app/api/getExperience) is the preview deployment link from vercel. That means, everytime you deploy to vercel it will create this preview link: https:// yourappname-(some unique deployment link).vercel.app.
However, in your api you pass ${process.env.NEXT_PUBLIC_BASE_URL} which will work on your local and probable on production, but it will not on your preview deployments (staging).
To avoid this, unfortunately you cannot only give /api/getExperience as only absolute URL's are supported. Therefore, I suggest the following approach by avoiding the API call as suggested in the [nextjs docs][1]:
you create an experience-queries.ts file in lib/
you add your GROQ query in there
export const getExperiences = groq`*[_type == "experience"]{..., technologies[]->}`
In index.ts, in getStaticProps you call getExperiences
const experiences = await sanityClient.fetch(getExperiences);
Note: Be careful with naming between experience (one single item) and experiences (a list of items) -> make sure you name if as you intend to get them.
[1]: https://nextjs.org/docs/basic-features/data-fetching/get-static-props#write-server-side-code-directly

using data from JSON in NodeJS

Hello i just started learning Nodejs and made a local server as a start
then i saw that most nodejs apps have config and package files i couldnt find any info on how to do a simple one or use JSON files so i tried myself this is what i got so far
this is the server file
var http = require('http');
var json = require('./package');
var fs = require('fs');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(addr.port);
console.log('server listening at', addr.address + ':' + addr.port);
and this is the json file
{
"addr": {
"address":"http://127.0.0.1",
"port":"8081"
}
}
i know that it will work with json.address and json.port
but when i added "addr" i thought it would simplify things with addr.port
so in short an explanation would be generously accepted on why it wont/shouldnt work or what im doing wrong
First of you should have a look at some tutorials or introduction sites like:
https://www.w3schools.com/nodejs/default.asp
Second:
The package.json file is the main configuration file of your nodeJS application. Thats the config file that defines your start point of your application as well as all included modules. simply use npm init to create a default package.json file with basic information.
Third:
If you require a json into your application as you did in your example the JSON is included hierarchically. Wich means The object you required has an attribute addr which itself is a new object with an attribute address.
So the correct way to access your information is json.addr.address based on your object description
you could also do something like this:
var network = require('./settings').addr;
console.log("ip => " + network.address);
console.log("port => " + network.port);
You need to list the parent object. You have put addr.address and addr.port, this means you are directly trying to access the addr object, but the this object doesn't exist. Try doing json.addr.address and json.addr.port and it should work.
var http = require('http');
var json = require('./package');
var fs = require('fs');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(json.addr.port);
console.log('server listening at', json.addr.address + ':' + json.addr.port);

Angular $http not working as expected

I am new to angular and trying to consume a basic back end service that I created using laravel. It is a basic Todo application and I am trying to fetch all the users resource for now.
If you go to the following URI, it will give back the all the users in the application:
Link to the URI
The code in my angular file looks like
var testing = angular.module('testing', []);
testing.controller('MainCtrl', function($scope, $http){
$scope.hello = "Hello World!";
$http.get('users.json').success(function(data){
$scope.users = data;
});
});
Now when I pass the URI in the parameter of $http.get method, I don't see any data. I have tried {{ users | json }} in my main index file to see the dump output. It simply doesn't work. But when I copy just the data array in the response and save it to a json file, it works perfectly.
Now the json that is returned from the web service has slightly more information like status and messages. How do I remove them when fetching them in Angular so that it works or is there a way I can have them returned and then extract them somehow from the whole data that has been returned?
If here http://todoapi.rohanchhabra.in/users is response from your server you should update your $http call to :
$http.get('users.json').success(function(response){
$scope.users = response.data;
});
if you requesting json file from your local iis make sure that it can serve .json files

Creating a non-REST JSON API server with node

I am relatively new to NodeJS, but I'm porting an existing API server written in PHP to use NodeJS. I started out looking at Express, but realised that with all the layout-rendering and templating stuff in Express, it wasn't suited for the task. Then I looked at Restify, but realised it's REST-ness wouldn't work with the model of this API.
I don't want anything that is tied to a database, or any specific way of setting out the API endpoints. Is the best solution to fully roll my own server, without the help of any libraries?
EDIT: Sorry, it seems I was unclear. I am trying to recreate the PHP API as close as possible, and the PHP version does not use REST. It has a few different PHP scripts which take some POST parameters.
If you just want a simple JSON API, Express is still an option. Layouts, temptating and middleware are optional, and you can just use simpler functions.
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(req, res) {
// req.body is an object with POST parameters
// respond with JSON
res.json(200, { data: 'payload' })
// or show an error
res.json(500, { error: 'message' });
});
app.listen(80);
That is one of the simplest solutions available. Unless you want to do request body parsing, checking the HTTP request method, other things yourself, then you can create your own server. That would look more like this:
var http = require('http');
http.createServer(function(request, response) {
if (request.method === 'POST') {
var data = '';
request.on('data', function(chunk) {
data += chunk;
});
request.on('end', function() {
// parse the data
});
}
}).listen(80);
A method like so would also require checking the path as well as other things that would be handled automatically in Express.

json rpc client for services module drupal

I am trying to create a json rpc client to access drupal services provided by services module for titanium.
function connect()
{
var loader = Titanium.Network.createHTTPClient();
var url = "http://10.0.2.2/service/services/json";
loader.open("POST",url);
loader.onload = function()
{
alert(this.responseText);
};
loader.send({"method:'system.connect'"});
}
This code results saying 'invalid method'.
I think the parsing of the data is not in the correct format.
Please help to resolve this problem.
Update your code like this :
loader.send({method:'system.connect'});
Refer Working with JSON Data in Drupal for more details .