greeting kings
i have api request that have cors problem. I'm able to solve by using proxy setup using nodejs. Unfortunately im trying to pass certain query parameter from my main js to app.js(nodejs proxy) so my api can have certain value from main js. How to solve this or should point me where should i read more.below is my code
main js
const inputValue = document.querySelector('input').value
//this value is maybeline
app.js(node.js proxy)
const express = require('express')
const request = require('request');
const app = express()
app.use((req,res,next)=>{
res.header('Access-Control-Allow-Origin', '*');
next();
})
app.get('/api', (req, res) => {
request(
{ url: 'https://makeup-api.herokuapp.com/api/v1/products.json?brand=covergirl' },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', message: err.message });
}
res.json(JSON.parse(body));
}
)
});
const port = process.env.PORT || 5500
app.listen(5500,()=>console.log(`listening ${port}`))
I want to pass inputValue as query to api in app.js
as
https://makeup-api.herokuapp.com/api/v1/products.json?brand=${type}
How to do it or point me any direction?
note:this api work withour cors problem.This is an example api..tq
You can use stringify method from qs module.
const { stringify } = require("qs");
app.get("/api", (req, res) => {
request(
{
url: `https://makeup-api.herokuapp.com/api/v1/products.json?${stringify(
req.params
)}`,
}
/// Rest of the code
);
});
Related
I made get request to Serp api, but learned that it is not possible to directly make fetch to Serp from React application, so I created local server and wrote logic for it, then I tested it with Postman and everything is fine. Then I had problems with CORS, I(guess) fixed them, but now I receive rejected promise on response and can't get rid of this. It gives
Unexpected end of input
Here is my server:
const SerpApi = require('google-search-results-nodejs');
const search = new SerpApi.GoogleSearch("myApiKey");
const express = require('express');
const app = express();
var allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.get('/:id', function (req, res) {
console.log("Made request");
const searchText = req.params.id;
const params = {
q: searchText,
tbm: "shop",
};
const callback = function (data) {
const objects = [...data["shopping_results"]];
console.log("call back worked");
if (!objects) {
console.log("ERROR 404");
res.status(404).send();
}
res.status(200).send(objects);
};
// Show result as JSON
search.json(params, callback);
});
app.use(allowCrossDomain);
app.listen(3001, function () {
console.log("App is listening for queries");
})
and my fetch:
import updateOnSearchRequest from '../redux/actions/updateOnSearchRequest';
export default function searchRequestToApi(queryText, dispatch) {
fetch(`http://localhost:3001/${queryText}`, {
mode: 'no-cors',
})
.then(res => console.log(res.json()))
.then(data => data ? dispatch(updateOnSearchRequest(data)) : {});
}
I receive error at console.log(res.json()) even though server works fine and doesnt give any errors
First of all, you need to remove mode: "no-cors", as mentioned in this answer, using it will give you an opaque response, which doesn't seem to return data in the body.
Second, move your app.use(allowCrossDomain); to the top so it's higher than app.get("/:id", function (req, res) {....
And lastly, you must remove console.log from .then(res => console.log(res.json())).
In summary, your server should be:
const SerpApi = require("google-search-results-nodejs");
const search = new SerpApi.GoogleSearch("myApiKey");
const express = require("express");
const app = express();
var allowCrossDomain = function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
};
app.use(allowCrossDomain);
app.get("/:id", function (req, res) {
console.log("Made request");
const searchText = req.params.id;
const params = {
q: searchText,
tbm: "shop",
};
const callback = function (data) {
const objects = [...data["shopping_results"]];
console.log("call back worked");
if (!objects) {
console.log("ERROR 404");
res.status(404).send();
}
res.status(200).send(objects);
};
// Show result as JSON
search.json(params, callback);
});
app.listen(3001, function () {
console.log("App is listening for queries");
});
And your fetch should be:
fetch(`http://localhost:3001/${queryText}`)
.then(res => res.json())
.then(data => data ? dispatch(updateOnSearchRequest(data)) : {});
So, let's say i have /api/cat/fact.js directory.
I wanna to get JSON Data from catfact.ninja
The thing is, i can't use require() or request() package, because if i used require, it would saya Couldnt Found Module..., and if i used request one, instead of returning the JSON Data that you beable to sees in catfact.ninja, it return JSON about the api, like hostname, port, which is i don't need
/API/api/cat/fact.js:
const express = require('express');
const app = express.Router();
const request = require('request')
app.use('', (req, res) => {
const src = 'https://catfact.ninja/fact';
const facts = request({
uri: src,
hostname: 'catfact.ninja',
port: 443,
path: '/fact',
method: 'POST',
json: 'fact'
}, (error, response, body) => {
if (error) console.log(error)
console.log(body, '\n\n' + response.fact)
})
console.log(facts);
return res.jsonp(facts)
})
module.exports = app;
You are returning JSON in the wrong place. It should be returned inside of the callback function.
Here's the solution:
const express = require('express');
const request = require('request-promise')
const app = express();
app.use('', async (req, res) => {
const src = 'https://catfact.ninja/fact';
try {
const response = await request({
uri: src,
port: 443,
method: 'GET',
json: true
})
return res.jsonp(response)
} catch (err) {
return res.jsonp(err)
}
})
function startServer() {
const port = 3000
app.listen(port, () => {
console.info('Server is up on port ' + port)
})
app.on('error', (err) => {
console.error(err)
process.exit(1)
})
}
startServer()
TIP: I suggest using request-promise npm package instead of request package as it provides async-await approach, which is cleaner. Else, you can continue using callback function as second request() function parameter.
I've read a lot of similar questions, but any answer worked for me.
I'm trying to send an audio in the body of a fetch request (in vuejs) as an ArrayBuffer, but when I print it in the server side, the body is undefined.
Client code:
export async function makeQuery(data) {
let bufferAudio = await data.arrayBuffer();
console.log(bufferAudio);
const response = await fetch(`/api/query`, {
method: 'POST',
//headers: {'Content-Type': 'audio/mp3'},
body: bufferAudio,
})
.catch(function(e) {
console.log("error", e);
});
return response;
}
Node Server code:
const express = require('express');
const path = require('path');
const app = express(), port = 3080;
app.post('/api/query', async (req, res) => {
query = req.body;
console.log('query ', query); // Here the body is undefined
/*
Do some processing...
*/
});
When I send a simple json string in the request body (and app.use(express.json()) in the server)it works. But not with the arraybuffer audio. Thanks in advance
I am trying to parse info from this link on my node.js project
https://stockx.com/api/products/nike-daybreak-undercover-black?includes=market
Im able to get info when I access the link through postman and going on the url on a web browser. However when I try accessing the request through my node.js project, it is saying access is denied. Any idea why?
Thanks.
Here is my code:
const express = require('express');
const request = require('request');
const cheerio = require('cheerio');
const axios = require('axios')
const app = express();
app.get('/', function(req, res){
let shoe =req.query.shoe;
let url = 'https://stockx.com/api/products/nike-daybreak-undercover-black?includes=market'
request(url, function(error, response, html) {
if (!error) {
var $ = cheerio.load(html);
console.log(html)
res.send();
}
});
});
app.listen('8080');
console.log('API is running on http://localhost:8080');
module.exports = app;
You just need to add "User-Agent" in the header. The website from which you are trying to get the data is denying all requests without User-Agent to avoid scrapers.
const options = {
url: 'https://stockx.com/api/products/nike-daybreak-undercover-black?includes=market',
headers: {
'User-Agent': 'request'
}
};
request(options, function(error, response, html) {
console.log('err: ', error);
if (!error) {
var $ = cheerio.load(html);
console.log(html)
res.send(html);
}
});
I have tried the following code and it works
// ...
app.get('/', function(req, res){
// let shoe =req.query.shoe;
let url = 'https://stockx.com/api/products/nike-daybreak-undercover-black?includes=market'
axios({
method : 'get',
url,
headers : { withCredentials: true, 'User-Agent' : 'Postman' }
})
.then(data => {
console.log('data', data.data);
})
.catch(err => {
console.log('err', err);
})
res.send().status(200);
});
I'm trying to send two json but It doesn't work. It prints TypeError: res.json is not a function but I don't get why It happens. Is there any ideas? Thank you !!
app.post('/danger', function response(req, res) {
let placeId = req.body.data;
let option = {
uri: 'https://maps.googleapis.com/maps/api/directions/json?',
qs: {
origin:`place_id:${placeId[0]}`, destination: `place_id:${placeId[1]}`,
language: 'en', mode: 'walking', alternatives: true, key: APIKey
}
};
rp(option)
.then(function(res) {
let dangerRate = dangerTest(JSON.parse(res), riskGrid);
res.json({ data: [res, dangerRate]});
})
.catch(function(err) {
console.error("Failed to get JSON from Google API", err);
})
});
Because you're overwriting your res variable in the .then of your rp function:
app.post('/danger', function response(req, res) { //see, "res" here was being overwritten
..
..
rp(option).then(function(response) { //change the variable name of "res" to "response" (or "turtles", who cares, just dont overwrite your up most "res")
I got this error message because I had the arguments in the wrong order in the handler method. (amateur's fault)
Wrong order: (res, req)
app.get('/json', (res, req) => {
res.json({
"message": "Hello json"
});
});
Right order: (req, res)
app.get('/json', (req, res) => {
res.json({
"message": "Hello json"
});
});
.json isn't a function. Unless you are using a library that makes it one, JavaScript uses JSON (with two methods .parse() and .stringify() one of which you use in the line above).
If you are trying to set an object property by the name of .json then it would be:
res.json = {data: [res, dangerRate]};
With new httpClient libary, you don't need to call .json() method, Just use this simple map instead of the json method.
.map(res => res );
check the sequence=>
If you have write nested res and you write (res,req) you get error.
order plays a very big role in app.get('/',(req,res)=>{ });
you can change the name instead of req and res but the second arg should be of res and the first should be of req
like app.get('/',(a,b)=>{ b.json({});
above syntax is res.json({}) ,we are sending a json file at '/'
const express = require('express');
const path = require("path");
const bodyParser = require('body-parser');
const app = express();
const PORT = 80;
app.use(bodyParser.urlencoded({
extended: false
}));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post('/api/v1', (req, res) => {
// const userName=req.body.name;
res.send("<h1>done</h1>");
console.log(req.body);
});
app.get("/api/v1/userdata", (req, res) => {
res.json({
name: "your_Name",
email: "your_Email",
password: "hexed",
});
});
app.listen(PORT, () => {
console.log("listening on port 80");
});