koa2 post always show Method Not Allowed? - koa

//server.js
const Koa = require('koa')
const app = new Koa();
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
const Router = require('koa-router');
const fs = require('fs');
const router = new Router();
const UserController = require('./server/controller/user.js');
const checkToken = require('./server/token/checkToken.js');
router.get('/user/login', async ctx => {
ctx.body = JSON.parse(fs.readFileSync( './pass.json'));
console.log(ctx.body);
});
router.post('/signin', async (ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p>Try again</p>`;
}
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8090, () => {
console.log('The server is running at http://localhost:' + 8090);
});
koa:2.52
koa-bodyparse:4.21
koa-router:7.4
when I type http://localhost:8090/user/login can get the Json data,but type http://localhost:8090/signin always show 405 Methods Not Allowed ,(debian firefxo) show Request Method "GET",response Allow: POST,Connection: "keep-alive"
I hope get your help.

I guess you shouldn't use the chrome to do the post cause when you type some url, the default method is GET not POST, you can check it out from the NETwork。 Try postman it will work.Sorry for my bad english,I hope it will help XD

Related

I am getting get polling-xhr.js:157 404 error on my website

I am using server.js code
const { startCon } = require('./server/WaConnection')
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const router = express.Router();
const { Server } = require('socket.io');
const io = new Server(server);
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: '50mb', parameterLimit: 1000000 }))
app.use(router);
require('./server/Routes')(router)
io.on('connection', (socket) => {
socket.on('StartConnection', async (device) => {
startCon(device, socket)
return;
})
socket.on('LogoutDevice', (device) => {
startCon(device, socket, true)
return
})
})
server.listen(process.env.PORT_NODE, () => {
console.log(`Server running on port ${process.env.PORT_NODE}`);
})
I am getting the error again and again that
enter image description here
I will be very thank full if you reslove my issue

Speech Service Authentication With 'Credentials' Via Webchat on Bot Framework V4

My bot is working fine while calling Speech Services using an authorization token + region pair.
Code snipped below.
webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({ authorizationToken, region });
However, the following warning message shows up on the browser:
botframework-webchat: "authorizationToken", "region", and "subscriptionKey" are deprecated and will be removed on or after 2020-12-17. Please use "credentials" instead.
How can migrate my authentication code to the new method?
Code samples are appreciated. Thx
This is the code I use. I run a server locally for calling the speech API that returns the token (and region).
In the Web Chat code, you simply need to pass the returned token and region in to createCognitiveServicesSpeechServicesPonyfillFactory(). Your code doesn't need to match mine, specifically. It is enough to do something like:
const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory( {
credentials: {
authorizationToken: authorizationToken,
region: region
}
} );
or, depending how you structure your credentials object,
{ credentials: credentials }
Sample code:
const path = require('path');
const restify = require('restify');
const request = require('request');
const bodyParser = require('body-parser');
const corsMiddleware = require('restify-cors-middleware');
const cors = corsMiddleware({
origins: ['*']
});
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
// Create HTTP server.
const server = restify.createServer();
server.pre(cors.preflight);
server.use(cors.actual);
server.use(bodyParser.json({
extended: false
}));
server.listen(process.env.port || process.env.PORT || 3500, function() {
console.log(`\n${ server.dl_name } listening to ${ server.url }.`);
});
server.post('/speechservices/token', async (req, res) => {
const options = {
method: 'POST',
uri: `https://${ process.env.SPEECH_SERVICES_REGION }.api.cognitive.microsoft.com/sts/v1.0/issueToken`,
headers: {
'Ocp-Apim-Subscription-Key': process.env.SPEECH_SERVICES_SUBSCRIPTION_KEY
}
};
request.post(options, (error, response, body) => {
if (!error && response.statusCode < 300) {
body = { region: process.env.SPEECH_SERVICES_REGION, authorizationToken: body };
res.send({
authorizationToken: body.authorizationToken,
region: body.region
});
console.log(`Someone requested a speech token...(${ response.statusCode })`);
} else if (response.statusCode >= 400 && response.statusCode < 500) {
res.send(response.statusCode);
} else if (response.statusCode >= 500) {
res.status(response.statusCode);
res.send('Call to retrieve token failed');
}
});
});
const getSpeechToken = async (credentials = {}) => {
const response = await fetch( `http://localhost:3500/speechservices/token`, {
method: 'POST',
} );
if ( response.status === 200 ) {
const { authorizationToken, region } = await response.json();
credentials['authorizationToken'] = authorizationToken;
credentials['region'] = region;
return credentials;
} else {
console.log('error')
}
}
const webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory( {
credentials: await getSpeechToken()
} );
render(
<div>
<ReactWebChat
directLine={directLine}
selectVoice={( voices, activity ) =>
activity.locale === 'en-US' ?
voices.find( ( { name } ) => /KatjaNeural/iu.test( name ) )
:
voices.find( ( { name } ) => /KatjaNeural/iu.test( name ) )
|| voices.find( ( { name } ) => /Apollo/iu.test( name ) )}
webSpeechPonyfillFactory={webSpeechPonyfillFactory}
/>
</div>,
document.getElementById( 'webchat' )
);
Hope of help!

Cannot POST ajax request

can anyone explain to me why i cannot post the ajax request. When i run this code the console appear POST http://localhost:8080/api/users 404 (Not Found), and in the networth part the preview is 404 not found
In the index.js file
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev.js');
var app = express();
var compiler = webpack(config);
var bodyParser = require('body-parser');
var users = require('./server/routes/users');
app.use(bodyParser.json());
app.use('/api/users', users);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(8080, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:8080');
});
and the users file
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
function validateInput(data) {
let errors = {};
if (Validator.isNull(data.username)){
errors.username = "This field is required";
}
if (Validator.isEmail(data.email)) {
errors.email = "Email is invalid";
}
if (Validator.isNull(data.password)){
errors.password = 'This field is required';
}
if (Validator.isNull(data.passwordConfirmation)){
errors.passwordConfirmation = 'This field is required';
}
if (Validator.equals(data.password, data.passwordConfirmation)){
errors.passwordConfirmation = 'Password must match';
}
return {
errors,
isValid: isEmpty(errors)
}
}
router.post('/api/users', (req, res) => {
console.log('runiing the router/post');
console.log(req.body);
const {errors, isValid} = validateInput(req.body);
if (!isValid) {
res.status(400).json(errors);
}
});
module.exports = router
in users.js file the function should be
router.post('/', (req, res) => {
console.log('runiing the router/post');
console.log(req.body);
const {errors, isValid} = validateInput(req.body);
if (!isValid) {
res.status(400).json(errors);
}
});
Because index.js have already resolved /api/users part in the request url http://localhost:8080/api/users at this point. So you only have to map after the /api/users in your users js file.
For example, if you have following function in users.js file
router.post('/:id', (req, res) => {
...
}
It will resole to the path http://localhost:8080/api/users/1
Edit
In your existing version,
router.post('/api/users', (req, res) => {
...
}
will resolve as http://localhost:8080/api/users/api/users

Can't use Express to send data back to client more than once

In my app, I send a post request to the server with data containing a CSV file:
$.ajax({
type:"POST",
contentType: "application/json",
url:"/",
data: JSON.stringify({fileData:My_CSV_FILE}),
success: function(csvJson) {
console.log('in the done block!');
//can use csvJson in this handler
});
});
Note: I'm posting to the home route, and I am able to get a response with the data converted from the server. The problem is that whether I run on localhost or Heroku, I am only able to trigger the POST request once, then I have to restart the server (even if I refresh the page). So I know the issue is with my route somewhere:
UPDATED TO INCLUDE FULL SERVER FILE:
'use strict';
const express = require('express');
const csvtojson = require('csvtojson');
const PORT = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const Converter = require('csvtojson').Converter;
var converter = new Converter({});
let app = express();
app.use(bodyParser.json({limit: '300kb'}));
app.use(express.static(__dirname +'/public'));
app.post('/',function(req,res) {
var csvFile = (req.body.fileData);
converter.fromString(csvFile, function(err, result) {
if(!err) {
console.log(result);
res.json(result);
}else {
res.json({error: 'Could not convert'});
}
})
});
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`);
});
I'm using Express 4. Again, everything works, but only once. When I run Heroku logs, or check the console on localhost I get:
Error: Can't set headers after they are sent.
But I don't understand how I'm re-setting them.
If wanting to run on localhost, here is a link to the projects github: https://github.com/qctimes/calendar_export
You should move the converter instantiation to be done inside the app.post callback method. This way it will instantiate a new object at every request.
This is is how your code should be:
'use strict';
const express = require('express');
const csvtojson = require('csvtojson');
const PORT = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const Converter = require('csvtojson').Converter;
let app = express();
app.use(bodyParser.json({limit: '300kb'}));
app.use(express.static(__dirname +'/public'));
app.post('/',function(req,res) {
var csvFile = (req.body.fileData);
var converter = new Converter({}); // instantiation is done here
converter.fromString(csvFile, function(err, result) {
if(!err) {
console.log(result);
res.send(result);
}else {
res.send({error: 'Could not convert'});
}
});
});
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`);
});

How do I post data using $resource using angularjs

I'm having a bit of a problem, I'm trying to do a http post request to my backend php. I'm new to angular and wanted to try the different REST method. I'm good with GET method. After this I will try UPDATE and DELETE method but for now I'm stuck on this. T__T.
Here a bit of the code in php
$data = array(
"email" => $email,
"password" => $this->input->post("password")
);
$insert_data = $this->player_registration->insert($data);
And here my factory
angular.module('myApp.services', ['ngResource'])
.factory('webService', function($resource){
var apiUrl = "http:domain.com/feed/"; //change this to web service
var factory = {};
factory.registerPlayer = function() {
return $resource( apiUrl + ':type', {type:'player'}, {
post: {method:'POST', params: {}}
});
};
factory.getPlayerByEmail = function () {
return $resource( apiUrl + ':type', {type:'player'}, {
get: {method: "GET", params: {}}
});
};
return factory;
})
And my controller
function registerController($scope, webService) {
$scope.inputs = {};
$scope.inputs.email = "testuser#domain.com";
$scope.inputs.password = "password";
var req = new webService.registerPlayer($scope.inputs);
req.save()
My app.js
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers'])
The default save() in $resources is actually $save().
var req = new webService.registerPlayer($scope.inputs);
req.$save()

Resources