Why I'm getting status code 302 on query response? - javascript

Why I'm getting status code 302 on query response and how i can fix it?
fetch method:
const grabApps = async () => {
const res = await fetch(`${spinnakerURL}/gate/applications`, {
redirect: "manual"
})
return res.data || []
}
vue.config.js
module.exports = {
devServer:
{
proxy:
{
'/gate':
{
target: 'https://spinstatus.zenoss.io',
changeOrigin: true,
onProxyReq: (proxyReq, req, res, options) =>
{
proxyReq.setHeader('Origin', 'https://spinstatus.zenoss.io')
}
}
}
}
}

Related

Can not get post result from node.js

I'm trying to get result from node.js api however, whenever i deploy my website, it gets html result like below.
but it works when it's on local. but not on the deployed website.
so i tried to use axios post then it gets 404 error.
and another api is work but when i write new api then it gets error.
this is my node.js
//this post work just fine .
app.post("/insertCodeVisual", async (req, res) => {
const { data } = await req.body;
const visualData = new CodeVisualData({
data: data,
});
try {
visualData.save((err, info) => {
res.send(info._id);
});
console.log("success");
} catch (error) {
console.log(error);
}
});
//but this post is not working
app.post("/api/database", async (req, res) => {
const { host, user, password, port, table, database } = await req.body;
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
port: port,
database: database,
});
try {
connection.connect();
} catch (error) {
res.send([["ERROR_CODE"], [error.code]]);
}
const sql = `SELECT * FROM ${table}`;
connection.query(sql, function (err, results) {
if (err) {
return res.send([
["ERROR"],
[`code : ${err.code}`],
[`errno : ${err.errno}`],
[`sqlMessage : ${err.sqlMessage}`],
]);
} else {
const parse = papa.unparse(results, {
quotes: false, //or array of booleans
quoteChar: '"',
escapeChar: '"',
delimiter: ",",
header: true,
newline: "\r\n",
skipEmptyLines: false, //other option is 'greedy', meaning skip delimiters, quotes, and whitespace.
columns: null, //or array of strings
});
const unparse = papa.parse(parse);
res.send(unparse.data);
}
});
});
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, "dist")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
React.js
this one is working absolutely
const insertData = async () => {
try {
if (confirm("are u sure? ")) {
axios
.post(`${backend}/insertCodeVisual`, {
data: {
client: client,
header: header,
},
})
.then(res => {
setJustSavedDataId(res.data);
});
} else {
return;
}
} catch (error) {
console.log(error);
}
};
this below is not working when i deployed .
const getDatabase = async () => {
const url = `${backend}/api/database`;
const api = await axios.post(url, db[id]);
const data = api.data;
try {
setInfo({ ...info, [id]: data });
} catch (error) {
console.log(error);
}
};
So i wonder what cases make this kind of issue.

Getting bad request for twitter request token endpoint and invalid request for create tweet endpoint?

I am trying to make requests on behalf of users so for that I have successfully generated oauth_access_token and oauth_access_token_secret but whenever I make call to tweets https://api.twitter.com/2/tweets
it gives following error message: post daata {"errors":[{"parameters":{},"message":"Requests with bodies must have content-type of application/json."}],"title":"Invalid Request","detail":"One or more parameters to your request was invalid.","type":"https://api.twitter.com/2/problems/invalid-request"}
code:
oauth.js:
const OAuth = require('oauth');
module.exports = (oauthCallback) => {
const TWITTER_CONSUMER_KEY = process.env.TWITTER_CONSUMER_KEY;
const TWITTER_CONSUMER_SECRET = process.env.TWITTER_CONSUMER_SECRET;
const twitter_request_token_url = 'https://api.twitter.com/oauth/request_token';
const twitter_access_token_url = 'https://api.twitter.com/oauth/access_token';
const _oauth = new OAuth.OAuth(
twitter_request_token_url,
twitter_access_token_url,
TWITTER_CONSUMER_KEY, // consumer key
TWITTER_CONSUMER_SECRET, // consumer secret
"1.0",
oauthCallback,
"HMAC-SHA1"
);
const oauth = {
post: (url, oauth_access_token, oauth_access_token_secret, post_body, post_content_type) => {
return new Promise((resolve, reject) => {
_oauth.post(url, oauth_access_token, oauth_access_token_secret, post_body, post_content_type,
(error, data, response) => {
console.log("post daata", data)
console.log("post response", response)
if (error) {
reject(error);
} else {
resolve({ data, response });
}
}
);
});
}
};
return oauth;
};
route.js:
router.post('/twitter/tweet', async (req, res) => {
try {
const { response } = await oauth.post('https://api.twitter.com/2/tweets', oauth_access_token, oauth_access_token_secret, { "text": "Hello World!" }, 'application/json')
console.log("response backend data", response.data);
res.status(201).send({ message: "Tweet successful" });
} catch (error) {
res.status(403).json({ message: "Missing, invalid, or expired tokens" });
}
});
I thought there is some problem with node-oauth package (FYR: https://github.com/ciaranj/node-oauth/issues/364#issue-1076029771) so I switched to oauth1a but then I am getting 400 bad request for request token endpoint
code:
const crypto = require('crypto');
const OAuth = require('oauth-1.0a');
const axios = require('axios');
router.post('/twitter/oauth/request_token', async (req, res) => {
try {
const oauth = OAuth({
consumer: {
key: process.env.TWITTER_CONSUMER_KEY,
secret: process.env.TWITTER_CONSUMER_SECRET
},
signature_method: 'HMAC-SHA1',
hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
});
const authHeader = oauth.toHeader(oauth.authorize({
url: `https://api.twitter.com/oauth/request_token?oauth_callback=http://localhost:3000`,
method: 'POST'
}));
console.log("authHeader", authHeader)
const response = await axios.post(`https://api.twitter.com/oauth/request_token?oauth_callback=http://localhost:3000`, {
headers: {
Authorization: authHeader["Authorization"]
}
});
console.log("response", response)
res.status(200).send({ status: "ok" });
} catch (error) {
console.log("error", error)
res.status(404).json({
message: "Twitter request token failed",
});
}
});
Not sure if this issue is specific to node-oauth but using axios I was able to tweet using twitter v2 APIs. Working code snippet added for reference:
const express = require('express');
const router = express.Router();
const OAuth = require('oauth-1.0a');
const axios = require('axios');
router.post('/twitter/tweet', async (req, res) => {
try {
const oauth = OAuth({
consumer: {
key: process.env.TWITTER_CONSUMER_KEY,
secret: process.env.TWITTER_CONSUMER_SECRET
},
signature_method: 'HMAC-SHA1',
hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
});
const token = {
key: '',
secret: ''
};
const authHeader = oauth.toHeader(oauth.authorize({
url: 'https://api.twitter.com/2/tweets',
method: 'POST'
}, token));
const data = { "text": "Hello world!!" };
await axios.post('https://api.twitter.com/2/tweets',
data,
{
headers: {
Authorization: authHeader["Authorization"],
'user-agent': "v2CreateTweetJS",
'content-type': "application/json",
'accept': "application/json"
}
}
);
res.status(201).send({ message: "Tweet successful" });
} catch (error) {
console.log("error", error)
res.status(403).send({ message: "Missing, invalid, or expired tokens" });
}
});

The form data perfectly adds data to DB in localhost but when hosted in Heroku it throws 400 error as bad request. I tried a lot but nothings works

It works fine when I use localhost. I am also using the correct URl in the frontend. It works for getting data and editing data but donot work when i try to post data using formdata using heroku URL.
Order.controller.js
const { cloudinaryUpload } = require('../middleware/cloudinary');
const Order = require('../Model/Order');
const addData= (req, res, next) => {
let data = JSON.parse(req.body.order);
data.files = req.files
console.log(data);
const OrderData = new Order({})
let mappedData = mapOrder(OrderData, data);
mappedData.save((err, saved) => {
if (err) {
console.log(err)
return next({
msg: err,
status: 400
})
}
res.json({
msg: "Submitted successfully"
})
})
// cloudinaryUpload(mappedData.referenceImage1.image)
// .then((response) => {
// mappedData.referenceImage1.image = response.public_id
// })
// .catch((error) => {
// console.log(err)
// return next({
// msg: error,
// status: 400
// })
// })
}
const GetData=(req, res, next) => {
Order.find({ orderStatus: "processing" }, (err, orders) => {
if (err) {
return next({
msg: err,
status: 404
})
}
res.json({
orders: orders
})
})
}
const EditData=(req, res, next) => {
let ID = req.query.id
Order.find({ OrderId: ID }, (err, order) => {
if (err) {
return next({
msg: err,
status: 404
})
}
order[0].orderStatus = "ReadyToPickUp"
order[0].save((err, updated) => {
if (err) {
return next({
msg: err
})
}
res.json({
order: updated
})
})
})
}
function mapOrder(OrderData, data) {
OrderData.orderType = data.OrderType
OrderData.customer.fullname = data.name;
OrderData.customer.phone = data.phone;
OrderData.customer.optionalPhone = data.optionalPhone || "";
OrderData.customer.address = data.address;
OrderData.cakeDescription.weight = data.Weight;
OrderData.cakeDescription.flavor = data.Flavor;
OrderData.cakeDescription.shape = data.Shape;
OrderData.cakeDescription.eggless = data.eggless;
OrderData.cakeDescription.messageoncake = data.messageoncake || "";
OrderData.orderStatus = "processing";
if (data.files[0]) {
OrderData.referenceImage1.image = data.files[0].filename
}
if (data.files[1]) {
OrderData.referenceImage2.image = data.files[1].filename
}
OrderData.referenceImage1.note = data.ImageNote1
OrderData.referenceImage2.note = data.ImageNote2
OrderData.deliveryDate = data.date;
OrderData.deliveryTime = data.time;
OrderData.amount = data.Amount;
OrderData.advancePaid = data.advance;
return OrderData;
}
module.exports = {
addData,GetData,EditData
};
Imagehandler.js
const multer = require('multer');
const path = require('path');
const storage= multer.diskStorage({
destination: function(req,file,cb){
cb(null,path.join(process.cwd(),'/uploads'))
},
filename : function(req,file,cb){
cb(null,Date.now()+'-'+file.originalname)
}
})
const fileFilter=(req,file,cb)=>{
let image = file.mimetype // mimetype is type of image/jpeg
let fileType = image.split('/')
if(fileType[0] === "image" ){
cb(null,true)
}
else{
req.fileError = true;
cb(null,false)
}
}
var upload = multer({ storage: storage, fileFilter: fileFilter})
module.exports = upload
app.route.js
const router = require('express').Router();
const upload = require('./middleware/imagehandler');
const {addData,EditData,GetData} = require('./api/order.controller');
router.post('/addorder',upload.array('images',3),addData)
router.put('/editorder',EditData)
router.get('/getorder',GetData)
module.exports = router
App.js
const express = require('express');
const app = express();
const path = require('path')
const cors = require('cors')
const orderRouter = require('./api/order.controller');
const dotenv = require('dotenv').config(); // it checks defalut .env file if present and cofigure it.
require('./db.initialize');
app.use(cors());
app.use('/api',orderRouter);
app.use('/files',express.static(path.join(process.cwd(),'/uploads')))
app.use((req,res,next)=>{
res.json({
msg: "Error occured",
satus: 400
})
})
// it recieves error from next and we can use the error information
app.use((error,req,res,next)=>{ // error handler
res.status(error.status || 400)
res.json({
msg : error.msg || "Error",
status: error.status || 400
})
})
app.listen(process.env.PORT || 8080,(err,done)=>{
if(err){
console.log("Server failed")
}
else{
console.log("Server Started at",process.env.PORT);
}
})
db.initialize.js
const mongoose = require('mongoose');
const {DB_NAME} = require('./configs/index.config')
let DBURL=`mongodb+srv://bibekdb:password#webapp.iqxjb.mongodb.net/${DB_NAME}?retryWrites=true&w=majority`
mongoose.connect(process.env.MONGODB_URI || DBURL,{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then((done)=>{
console.log("Heroku");
console.log("DB connected successfully..",process.env.DB_NAME);
})
.catch((error)=>{
console.log("Db connection failed")
})
httpClient.js
I am hitting the correct API using xhr and sending data using formdata. I dont know what i am missing
import axios from 'axios';
const base_URL = process.env.REACT_APP_BASE_URL;
const https = axios.create({
baseURL: process.env.REACT_APP_BASE_URL,
timeout: 10000,
timeoutErrorMessage: "Server timeout",
responseType: "json",
headers: {
'Content-Type': "application/json"
}
})
const GET =(url)=>{
return https.get(url)
}
const EDIT =(url,params)=>{
return https.put(url,null,{
params
})
}
const Upload = (method, url, data = {}, files = []) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const formdata = new FormData()
const orderData = JSON.stringify(data);
formdata.append('order',orderData)
files.forEach((file, index) => {
formdata.append('images', file, file.name)
})
xhr.onreadystatechange=()=> {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.response)
}
else {
reject(xhr.response)
}
}
}
xhr.open(method, `${base_URL}${url}`)
xhr.send(formdata);
})
}

Node TypeError: checkURL is not a function

Why does it produce a TypeError checkURL is not a function. i searched few older question too but couldn't figure out why it shows the error.
const Server = {
checkURL: function(url, matchWith) {
return url === matchWith;
},
respond: function(res, status, cType, data ) {
res.writeHead(status, {
'Content-Type': cType,
})
res.write(data)
res.end()
},
streams: function(req, res) {
if (this.checkURL(req, '/')) {
this.respond(res, 200, 'text/html', `<h2>HELLO</h2>`)
}
},
init: function(PORT) {
require('http')
.createServer(this.streams)
.listen(PORT, () => {
console.log(`Listening on <${PORT}>`)
})
return this
}
}
module.exports = Server

Cookie problem with node/apollo/express server after deploying to Heroku

I'm building node js server with apollo and front end with next.js/apollo client. My problem is that on localhost everything is works as it must be, but after deploying to Heroku cookies not set. I'm getting the data from server and redirects me to the home page, but after page reload it redirects me to login page again.
This is apollo server code
import cors from 'cors'
import Redis from 'ioredis'
import dotenv from 'dotenv'
import express from 'express'
import mongoose from 'mongoose'
import session from 'express-session'
import connectRedis from 'connect-redis'
import { ApolloServer } from 'apollo-server-express'
import typeDefs from './schema'
import resolvers from './resolvers'
dotenv.config({
path: `.env.${process.env.NODE_ENV}`,
})
const port = process.env.PORT || 4000
const dev = process.env.NODE_ENV !== 'production'
const RedisStore = connectRedis(session)
const startServer = async () => {
await mongoose
.connect(process.env.DB_URL, { useNewUrlParser: true })
.then(() => console.log(`🔗 MongoDB Connected...`))
.catch(err => console.log(`❌ MongoDB Connection error: ${err}`))
const app = express()
const server = new ApolloServer({
typeDefs,
resolvers,
playground: !dev
? false
: {
settings: {
'request.credentials': 'include',
},
},
context: ({ req, res }) => ({ req, res }),
})
app.disable('x-powered-by')
app.set('trust proxy', 1)
app.use(
cors({
credentials: true,
origin:
process.env.NODE_ENV === 'production'
? process.env.FRONT_END_URL
: 'http://localhost:3000',
}),
)
app.use((req, _, next) => {
const authorization = req.headers.authorization
if (authorization) {
try {
const cid = authorization.split(' ')[1]
req.headers.cookie = `cid=${cid}`
console.log(cid)
} catch (err) {
console.log(err)
}
}
return next()
})
app.use(
session({
store: new RedisStore({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
pass: process.env.REDIS_PASS,
}),
name: process.env.SESS_NAME,
secret: process.env.SESS_SECRET,
saveUninitialized: false,
resave: false,
cookie: {
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
secure: false,
},
}),
)
server.applyMiddleware({ app, cors: false })
app.listen({ port }, () =>
console.log(
`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`,
),
)
}
startServer()
and this is the resolvers
import gravatar from 'gravatar'
import bcrypt from 'bcrypt'
import { User } from '../models'
import { isAuthenticated, signOut } from '../auth'
import { loginSchema, registerSchema } from '../utils'
export default {
Query: {
users: (parent, args, { req }, info) => {
isAuthenticated(req)
return User.find({})
},
user: (parent, { id }, context, info) => {
isAuthenticated(req)
return User.findById(id)
},
me: (parent, args, { req }, info) => {
isAuthenticated(req)
return User.findById(req.session.userId)
},
},
Mutation: {
signUp: async (parent, args, { req }, info) => {
// isAuthenticated(req)
args.email = args.email.toLowerCase()
try {
await registerSchema.validate(args, { abortEarly: false })
} catch (err) {
return err
}
args.avatar = await gravatar.url(
args.email,
{
protocol: 'https',
s: '200', // Size
r: 'pg', // Rating
d: 'mm', // Default
},
true,
)
args.password = await bcrypt.hash(args.password, 12)
const user = await User.create(args)
req.session.userId = user.id
return user
},
signIn: async (parent, args, { req }, info) => {
// isAuthenticated(req)
const { email, password } = args
try {
await loginSchema.validate(args, { abortEarly: false })
} catch (err) {
return err
}
const user = await User.findOne({ email })
if (!user || !(await bcrypt.compare(password, user.password))) {
throw new Error('Incorrect email or password. Please try again.')
}
req.session.userId = user.id
return user
},
signOut: (parent, args, { req, res }, info) => {
return signOut(req, res)
},
},
}
and here is apollo client on front end (I'm using with-apollo-auth example from next.js)
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { createHttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import fetch from 'isomorphic-unfetch'
let apolloClient = null
if (!process.browser) {
global.fetch = fetch
}
function create(initialState, { getToken }) {
const httpLink = createHttpLink({
uri:
process.env.NODE_ENV === 'development'
? 'http://localhost:4000/graphql'
: process.env.BACK_END_URL,
credentials: 'include',
})
const authLink = setContext((_, { headers }) => {
const token = getToken()
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
}
})
return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser,
link: authLink.concat(httpLink),
cache: new InMemoryCache().restore(initialState || {}),
})
}
export default function initApollo(initialState, options) {
if (!process.browser) {
return create(initialState, options)
}
if (!apolloClient) {
apolloClient = create(initialState, options)
}
return apolloClient
}
Thanks in advance.

Categories

Resources