I trying to do a swagger documentation for an Express API and Firebase database, when I make request to my database in local with postman it work, but with the swagger interface I get this error:
Failed to fetch.
Possible Reasons:
CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
For my documentation I use swagger-autogen and swagger-ui-express
there is a example for the login endpoint:
const app = express();
const port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(
cors({
origin: `http://localhost:${port}`,
methods: ["GET", "POST", "DELETE", "PUT", "PATCH"],
credentials: true,
})
);
app.use(helmet());
app.use(morgan("combined"));
app.get("/", (req, res) => {
res.status(200).json({ message: "Welcome" });
});
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerFile, options));
swagger.js
const outputFile = "schemas/swagger.json";
const endpoints = \["routes/auth.js", "routes/menus.js"\];
const doc = {
info: {
version: "1.0.0",
title: "Menus API documentation",
description: "Documentation of MenusAPI",
termsOfService: "http://swagger.io/terms/",
contact: {
email: "contact#toto.com",
},
license: {
name: "Apache 2.0",
url: "http://www.apache.org/licenses/LICENSE-2.0.html",
},
},
servers: \[
{
url: "https://localhost:8081/menusapi/api/v1/",
},
\],
host: "/",
consumes: \["application/json"\],
produces: \["application/json"\],
securityDefinitions: {
OAuth2: {
type: "oauth2",
flows: {
authorizationCode: {
authorizationUrl: process.env.AUTH_UTI,
tokenUrl: process.env.TOKEN_URI,
scopes: {
read: "Grants read access",
write: "Grants write access",
},
},
},
},
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
},
},
"#definitions": {
AddUser: userSchema.registration,
Login: userSchema.login,
Menus: menusSchema,
},
};
swaggerAutogen(outputFile, endpoints, doc).then(() =\> {
require("../app");
});
routes/auth.js
router.post("/login", auth.login);
controllers/auth_controller.js
exports.login = async (req, res) =\> {
/\* #swagger.tags = \['Auth'\]
\#swagger.description = 'Service to login';
\#swagger.summary = "Service to login a user to the app";
\#swagger.security = \[{
"OAuth2": \[
'read',
'write'
\]
}\]
\#swagger.responses\[200\] = {
description: 'Login sucess',
schema: {
"message": "Successfully connected!",
"jwt": "A very long token",
"refresh_jwt": "An other long token"
}
}
console error:
throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}. ` +
^
Error: Value for argument "value" is not a valid query constraint. Cannot use "undefined" as a Firestore value
I looked everywhere but I really don't know what to do
Related
I have already done this but Idk why when I try to apply it again in another code it does not work. So I have this code "Client side"
const response = await fetch("/api/ipfs", {method: "POST", DATA: "holaaaa"});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const result = await response.json()
console.log(result.result)
And this one that is the "Server side"
function uploadIPFS(req, res) {
axios.get(req.body).then(r => {
let metadata = r.data
res.status(200).json({ metadata: metadata });
}).catch(err => console.error(err))
}
export default function handler(req, res) {
if (req.method==='POST') {
uploadIPFS(req, res);
}
}
This is working with another api file I have, so I implement another file that is this one and in another function of the client side make a call to the new api file, the problem is that the variable I want to pass from client to server is the body one, the one that says "holaaaa", is it not working and it throws this error.
API resolved without sending a response for /api/ipfs, this may result in stalled requests.
Error: Cannot read properties of null (reading 'replace')
at dispatchHttpRequest (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\adapters\http.js:161:23)
at new Promise (<anonymous>)
at httpAdapter (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\adapters\http.js:49:10)
at dispatchRequest (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\dispatchRequest.js:58:10)
at Axios.request (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\Axios.js:109:15)
at Axios.<computed> [as get] (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\Axios.js:131:17)
at Function.wrap [as get] (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\helpers\bind.js:9:15)
at uploadIPFS (webpack-internal:///(api)/./pages/api/ipfs.js:17:11)
at handler (webpack-internal:///(api)/./pages/api/ipfs.js:37:9)
at Object.apiResolver (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\next\dist\server\api-utils\node.js:184:15) {
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.27.2'
},
method: 'get',
url: '',
data: undefined
},
url: '',
exists: true
}
any idea abt this?
The request to your API is made, but you are not adding anything to the request body. I think you need to change your DATA property in your fetch call to body:
const response = await fetch("/api/ipfs", { method: "POST", body: "holaaaa" });
Also, since you are passing that body parameter to the axios.get() method in your API handler, I assume it's supposed to be a URL?
My code works as below in my localhost. What I'm trying to do is put my password in my .envlocal but it won't work.
working code
export default function (req, res) {
let nodemailer = require('nodemailer')
const transporter = nodemailer.createTransport({
port: 465,
host: "smtp.gmail.com",
auth: {
user: 'myEmail#gmail.com',
pass: 'password123',
},
secure: true,
});
const mailData = {
from: 'keshibatmail#gmail.com',
to: 'kensukeshibata#gmail.com',
subject: `Message From ${req.body.name}`,
text: req.body.message + " | Sent from: " + req.body.email,
html: `<div>${req.body.message}</div><p>Sent from: ${req.body.email}</p>`
}
transporter.sendMail(mailData, function (err, info) {
if(err)
console.log(err)
else
console.log(info);
})
console.log(req.body)
res.send('success')
}
What I tried.
My next.js is
"next": "10.x"
,
So I should be able to use this since my next.js is higher than 9.4 https://nextjs.org/docs/api-reference/next.config.js/environment-variables
I made .env.local file
NEXT_PUBLIC_PASSWORD=password123
then process.env.NEXT_PUBLIC_PASSWORD
I tried without NEXT_PUBLIC_ as well.
I get this error.
response: '535-5.7.8 Username and Password not accepted.
const transporter = nodemailer.createTransport({
port: 465,
host: "smtp.gmail.com",
auth: {
user: myEmail#gmail.com,
pass: process.env.NEXT_PUBLIC_PASSWORD,
},
secure: true,
});
We have got rw_ads permissions for an app. Through that app We have taken access_token with all given permissions.
As mentioned in the documentation, we have rw_ads permission, but If we try to create/update campaign we are getting the below error.
{
"serviceErrorCode": 100,
"message": "Not enough permissions to access: POST /adCampaignsV2/sdafnk",
"status": 403 }
var request = require("request");
var options = { method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2/sdafnk',
headers:
{ 'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json' },
body:
{ patch:
{ '$set':
{ runSchedule: { end: 1548405000000, start: 1547713800000 },
status: 'ACTIVE' } } },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Code for creation of campaign is mentioned below
var request = require("request");
var options = {
method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2',
headers: {
'Authorization': 'Bearer <accessToken>',
'Content-Type': 'application/json'
},
body: {
account: 'urn:li:sponsoredAccount:<accountId>',
audienceExpansionEnabled: false,
costType: 'CPM',
creativeSelection: 'OPTIMIZED',
dailyBudget: { amount: '200', currencyCode: 'INR' },
locale: { country: 'IN', language: 'en' },
name: 'Campaign text ad test',
objectiveType: 'WEBSITE_TRAFFIC',
offsiteDeliveryEnabled: false,
runSchedule: { end: 1547708400000, start: 1547967600000 },
type: 'TEXT_AD',
unitCost: { amount: '10', currencyCode: 'INR' },
status: 'PAUSED'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
When you perform a partial update, the header X-RestLi-Method must be included in the request and set to PARTIAL_UPDATE.
Also if you use implicit grant-type, check if you have defined the scope correctly at the start. if you use client-credentials grant-type check if the account has the right permissions.
Direct Sponsored Content can be created by:
Ad Account Users with a role higher than VIEWER. Organization users
with DIRECT_SPONSORED_CONTENT_POSTER or ADMINISTRATOR roles.
also the code you added in this question is for Reactivating a campaign. not for updating/creating one.
I am using Ionic 2 with HTTP native module to make a post request to FCM server for push notifications. The code I am using is:
HTTP.post(
"https://fcm.googleapis.com/fcm/send",
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token",
},
{
Authorization: {
key: "AUTHORIZATION KEY HERE"
}
})
Its giving me an error:
Unimplemented console API: Unhandled Promise rejection:
Unimplemented console API: Error: Uncaught (in promise): [object Object]
I tried the post request with Postman, it works perfectly fine delivering push notifications.
The code with Postman is:
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=Authorisation Key
Cache-Control: no-cache
Postman-Token: 446e253b-179a-d19b-21ea-82d9bb5d4e1c
{
"to": "Device Token",
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
}
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
}
Questions:
I am unable to add content-type to the header in the HTTP post request, but it works with postman.
If I try to add a function(response) { to get the response from the server, it gives me an error. The documentation for the same is at https://github.com/wymsee/cordova-HTTP
why are you using HTTP native module? Angular has a built in Http.
Using this one (importing HttpModule from #angular/http in your NgModule) you can just call
import { Http, Headers } from '#angular/http';
......
constructor(public http: Http) { }
sendPushNotification(deviceId: string) {
let url = 'https://fcm.googleapis.com/fcm/send';
let body =
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token"
};
let headers: Headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'key='+this.someKey
});
let options = new RequestOptions({ headers: headers });
console.log(JSON.stringify(headers));
this.http.post(url, body, headers).map(response => {
return response;
}).subscribe(data => {
//post doesn't fire if it doesn't get subscribed to
console.log(data);
});
}
push.on('notification', (data) => {
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: data.title,
message: data.message,
buttons: [{
text: 'Ignore',
role: 'cancel'
}, {
text: 'Go to',
handler: () => {
//TODO: Your logic here
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
});
push.on('error', (e) => {
alert(e);
});
});
I am trying to upload files using edgee:slingshot, but I have several errors. I have did everything as described in github page. This is my settings on server:
Slingshot.GoogleCloud.directiveDefault.GoogleSecretKey = Assets.getText('google-cloud-service-key.pem');
Slingshot.createDirective("myFileUploads", Slingshot.GoogleCloud, {
bucket: 'dossum-app',
GoogleAccessId: "GOOGXXXX",
GoogleSecretKey: "qZEsLZ/NiXXXXXXXXXXXXUW8NVjSvRb8SgdxXXXXX2",
acl: 'bucket-owner-full-control',
authorize: function() {
if (!this.userId) {
var message = 'Please login before posting file';
throw new Meteor.Error('Login Required', message);
}
return true;
},
key: function(file) {
var user = Meteor.users.findOne(this.userId);
return user.username + '/' + file.name;
}
});
And this is cors.json:
[{"origin": ["http://localhost:3000", "http://qnekt.zehinz.com"], "responseHeader": ["Origin", "Accept", "X-Requested-With", "Authorization", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token"], "method": ["GET", "HEAD", "DELETE", "PUT", "POST", "HEAD"], "maxAgeSeconds": 3600}]
If I run with above configuration I get this error without any details: {error: 500, reason: "Internal server error"....
I have tried to comment this line: //GoogleSecretKey:"qZEsLZ/NiEkXo641XHIUW8NVjSvRb8SgdxIyYcV2"
This time I receive this error:
{error: "Forbidden - 403", reason: "Failed to upload file to cloud storage", details: undefined ...
Can anyone please guide me?
Where should I get GoogleAccessId if I am using .pem file instead of GoogleSecretKey?
What should be the cors.json file for file uploading and public reading?
I had troubles with edgee:slingshot and Google Cloud Storage. But this settings now work for me:
//server
Slingshot.GoogleCloud.directiveDefault.GoogleSecretKey = Assets.getText('google-cloud-service-key.pem');
Slingshot.createDirective('avatarUploader', Slingshot.GoogleCloud, {
bucket: 'my_bucket',
GoogleAccessId: 'xxxxxxxxxxxxxx#developer.gserviceaccount.com',
acl: 'public-read',
authorize: function() {
if (!this.userId) {
var message = 'Please login before posting file';
throw new Meteor.Error('Login Required', message);
}
return true;
},
key: function(file) {
var user = Meteor.users.findOne(this.userId);
var ext = file.type.split('/')[1];
return user.username + '/' + randomString(20) + '.' + ext;
}
});
//CORS settings
[
{
"origin": ["*"],
"responseHeader": ["*"],
"method": ["GET", "POST", "PUT", "HEAD"],
"maxAgeSeconds": 3000
}
]
For details look here.