Unable to fetch Yelp API when MERN stack - javascript

I set up the my express backend to fetch restaurant with the dish name from Yelp API, and receive the request from my frontend, but browser gave me POST http://localhost:5000/api/search/ net::ERR_ABORTED 403 (Forbidden).
Frontend:
item would be the dish name
let backend
if (document.location.hostname === 'localhost') {
backend = 'http://localhost:5000/'
} else {
backend = 'https://meals4yo.herokuapp.com/'
}
useEffect(() => {
fetch(`${backend}api/search/`, {
method: 'post',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({term: item})
})
.then(response => response.json())
.catch(err => {
console.log(err)
})
},[])
Backend:
app.post('/api/search', function(req, res) {
debugger
let request = axios.create({
headers: {
Authorization: `Bearer API_KEY`,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS"
}
})
request
.get('https://api.yelp.com/v3/businesses/search', {
params: {
term: req.body.term,
location: "nyc"
}
})
.then(response => {
console.log(response.data)
res.json(response.data.businesses)
})
.catch (err => {
console.log(err)
})
})
I tried to add mode: "no-cors" and used axios to do the fetch in the frontend, none of those work

Related

CORS response when sending a DELETE request

I am trying to send a DELETE request to my backend server, but I keep getting this response printed to my console:
Response {type: 'cors', url: 'http://localhost:3003/delete', redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3003/delete"
[[Prototype]]: Response
I don't know why this is happening.
server.js
const express = require('express')
const knex = require('knex')
const cors = require('cors')
const db = knex({
client: 'pg',
connection: {
host: '127.0.0.1',
user: 'postgres',
password: 'psql',
database: 'blogspot',
port: 5432
}
});
const app = express();
app.use(express.json())
app.use(cors())
// Delete Blog
app.delete('/delete', (req, res) => {
const {id} = req.body;
db.select('*').from('blogs')
.where({
id: id
})
.del()
.then(() => {
res.json('Deleted Successfully')
})
.catch(err => res.status(404).json('An error occured'))
})
fetchAPI.js
function deleteBlog (blog) {
fetch('http://localhost:3003/delete', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(blog)
}).then(resp => {
console.log(resp)
if (resp === 'Deleted Successfully') {
navigate(0)
} else if (resp === 'An error occured') {
console.log('Something went wrong')
} else {
console.log('ERROR')
}
})
}
I keep getting 'ERROR' printed to my console along with the cors response I pasted above. When I refresh, I find that the blog has been deleted, but the response was definitely an error since navigate(0) wasn't run and ERROR was printed to my console. I have tried removing the 'Content-Type': 'application/json' header and sending the id as request params instead but I got the same error.
The fact that the response is of type "cors" just means that some contents are filtered by CORS policy (see https://developer.mozilla.org/en-US/docs/Web/API/Response/type) but you didn't get any error code, the statusCode is 200.
Since your response content type is JSON, you must also resolve the json parsing before reading the response:
function deleteBlog(blog) {
fetch('http://localhost:3003/delete', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(blog)
})
.then(data => data.json())
.then(resp => {
// I also suppose that you will more likely find
// your "Deleted successfully" in the resp.body property, so :
if (resp.body === 'Deleted Successfully') {
navigate(0)
} else if (resp.body === 'An error occured') {
console.log('Something went wrong')
} else {
console.log('ERROR')
}
})
}

Getting net::ERR_ABORTED 401 in my react app

Below is my react code snippet. I have verified that the token is correct using postman. Does anyone have ideas what might be missing here ?
export async function getData() {
const url = buildUri();
const auth = "Bearer " + await getAccessToken(); // api call to get access token
console.log("Using auth: ", auth);
var res = fetch(url, {
method: 'GET',
mode: 'no-cors',
headers: {
"Content-Type": "application/json",
"Authorization": auth
}
}).then(response => {
return response.json();
}).catch((error) => {
console.log("Error getting data: ", error);
});
console.log('got res: ', res);
}

'Access-Control-Allow-Credentials' header in the response is ' ' which must be 'true' when the request's credentials mode is 'include' [duplicate]

This question already has answers here:
'Access-Control-Allow-Credentials' header in the response is '' which must be 'true'
(2 answers)
Closed 2 years ago.
I am learning server-client communication in the course of making MMORPG project.
*update: server side code is edited.
This is server side code.
router.post('/login', async (request, response, next) => {
passport.authenticate('login', async (error, user) => {
try {
if (error) {
return next(error);
}
if (!user) {
return next(new Error('email and password are required'));
}
request.logIn(user, { session: false }, (err) => {
if (err) {.....
This is client side code
function postData(url, data = {}) {
return fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
body: JSON.stringify(data),
}).then((response) => response.json());
}
login() {
const loginValue = this.loginInpout.value;
const passwordValue = this.passwordInput.value;
postData('http://localhost:4000/login', { email: loginValue, password: passwordValue })
.then((response) => {
if (response.status === 200) {
this.startScene('Game');
} else {
console.log(response.message);
window.alert('invald username or password');
}
}).catch((error) => {
console.log(error.message);
window.alert('invald username or password');
});
}
when login() function is called, fetch() function throws this message in browser console.
(http://localhost:4000/login) is server side and (http://localhost:8000) is client side.
Access to fetch at 'http://localhost:4000/login' from origin 'http://localhost:8000'
has been blocked by CORS policy: Response to preflight request doesn't pass access
control check: The value of the 'Access-Control-Allow-Credentials' header in the
response is '' which must be 'true' when the request's credentials mode is 'include'.
LoginScene.js:48 POST http://localhost:4000/login net::ERR_FAILED
Failed to fetch <<-- fetch error message on browser console
I tried to fix it many different ways with no good outcome.
Try the following code:
import express from "express";
import http from "http";
const app = express();
const server = http.createServer(app);
const sio = require("socket.io")(server, {
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin,
"Access-Control-Allow-Credentials": true
};
res.writeHead(200, headers);
res.end();
}
});
sio.on("connection", () => {
console.log("Connected!");
});

Make Discord Request With NodeJS (Change Vanity Discord)

I'm making a bot that can change url code with a request, but i've tried something, and it's only returning the current invite code
My code:
fetch('https://www.discord.com/api/v6/guilds/762359120031907871/vanity-url', {
method: 'POST',
headers: { 'Authorization': 'Bot ' + client.token, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"test458"
})
})
.then(res => res.json())
.then(json => { console.log(json)})
And it's returning
{ code: 'cherrys', uses: 0 }
I just want to change the code, but idk how i can do that, and when i try with a user token it say
401: Unauthorized
Can someone help me with that?
The prefix Bot on the Autorization header is only for Bots, if you want to use a user token, you need to use Bearer prefix instead of the bot ones.
fetch('https://www.discord.com/api/v6/guilds/762359120031907871/vanity-url', {
method: 'POST',
headers: { 'Authorization': `Bearer ${client.token}`, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"test458"
})
})
.then(res => res.json())
.then(json => { console.log(json)});

How do you make an API request using browser fetch with token auth

I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
You are not sending headers properly.
Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})

Categories

Resources